I have a directory with files that have to be protected. Protection is made by standard HTTP Basic Authentication (.htaccess, .htpasswd etc). With code below i can get content of protected page, but nothing else (“session / login” expires at once). I need to access that page and download files. How to login to protected area and stay on that page using php (or javascript/ajax) ?
<?php
// HTTP authentication
$url = "http://localhost/protected_files/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "login:password");
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
The same using jQuery ajax:
var username = $("input#username").val();
var password = $("input#password").val();
function make_base_auth(user, password) {
var hash = btoa(user + ':' + password);
return "Basic " + hash;
}
$.ajax
({
type: "GET",
url: "http://localhost/protected_files/",
headers: {
'Authorization' : make_base_auth(username, password)
},
success: function (data){
$('body').html(data);
}
});
Your PHP script uses CURL to read a file that is located in a directory protected by HTTP Basic Authentication and echo it to the screen. If your PHP is located in your web root, and your protected directory is in a subdirectory called “protected”, the user’s browser is never actually re-directed into the protected directory. The user’s browser stays in the web root.
Moreover, the user’s browser has never authenticated. Only your web server has authenticated via your PHP script. Think of it like this, your web server acted as a human and used a PHP based web-browser of sorts to authenticate. The person sitting at their computer at home never authenticated their web browser. Apache authenticated, read the contents of that file, and passed it along to the end user as sort of a proxy.
After the initial script loads a page. Any anchors tags with href attributes pointing to files located within the “protected” folder will bring up that popup asking the user to authenticate. You are mistaking this as an expired session. This is happening because the server hosting the PHP script (not the end user’s computer) is authenticated in your PHP script. The end user’s computer has yet to authenticate even once. After they enter their credentials, they should be good for the rest of the session.
What you are asking is impossible. The user will always be prompted for a username and password whenever they click on a link. Why not just have them log in? If the files need to be password protected, why are you circumventing the protection. You may need to rethink your approach.
Broken down further: This is your PHP script.
Now, the end user clicks on a link to download a file
Here is the conversation your JavaScript example would have.
End user types in username and password, clicks on submit button
End user clicks on a link.