Requirement
Many times, in a software project, a developer is required to access a file in a restricted folder as an HTTP request with allow_url_open in php.ini set to OFF. This is for Windows Environment.
Solution
The viable solution here is to use cURL, a command line tool for transferring date with URL syntax.
How to make a folder restricted with .htaccess and .htpasswd?
- In Project Folder, create a folder and call it Private
- In an editor, create a new file called .htaccess with following lines of code and save it inside Private folder
AuthName “Restricted Area”
AuthType Basic
AuthUserFile D:/wamp/www/TryPhp/private/.htpasswd
require valid-user
- Go to the following URL http://www.htaccesstools.com/htpasswd-generator-windows/
- Enter a username and password and it would generate a string. Copy the string
- Create a new file and paste the string generated from above step and save it as .htpasswd in Private folder
- Try to access the folder with the weburl and it would prompt for a username and password
Access the folder with cURL
- Create a file in the root of the project and put the following code in it to access the content of any file within Private folder
<?php
$curlObj = curl_init();
$username = “{chosen username}”;
$password = “{chosen encrypted password}”;
curl_setopt($curlObj, CURLOPT_URL, “http://localhost/{Project Name}/private/{PHP File}”);
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlObj, CURLOPT_USERPWD, “$username:$password”);
curl_setopt($curlObj, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$output = curl_exec($curlObj);
$transferInfo = curl_getinfo($curlObj);
curl_close($curlObj);
print_r( $transferInfo );
?>
Note: Replace the following variables in the above code
- {chosen username}
- {chosen encrypted password}
- {Project Name}
- {PHP File}
The line curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, true); enables to retrieve the data in a variable from a remote file.
Thus in this way, you are able to successfully access a remote file using cURL.