I am trying to protect an upload script with a password using AJAX + PHP + .htaccess.
My test website is at http://scrabble.stats.org.pl/test/gcg/. If you choose one option from the dropdown list, a table will appear. Then, in the rightmost column, you'll see "Dodaj" ("add") buttons. Their "change" event is handled with AJAX at line #25 (a minimal version below):
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$('.upload').on('change', function(event) {
var file_data = $(event.target).prop('files')[0];
//console.log(file_data);
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
var response = $.parseJSON(php_script_response);
if ( response.status == 'error') {
alert( response.errormsg );
}
else {
$(event.target).closest('.fileUpload').hide();
}
}
});
});
}
};
upload.php
can be found here. It just saves the contents of the uploaded file to a database. It returns a $response_array
with success
or error
states.
Now, I know how to protect a folder on my server with a .htaccess file and it works fine (check out http://scrabble.stats.org.pl/test/gcg/upl):
AuthType Basic
AuthUserFile "/usr/auth.passwd"
require valid-user
AuthName "Protected site"
Is it possible to protect upload.php
only, so that the website prompts for a password when a user clicks on that "Add" button?
I found this, this and this and tried those solutions, but they don't seem to work. Usually I am getting this error in Chrome console:
http://scrabble.stats.org.pl/test/gcg/upload/upload.php
Failed to load resource: the server responded with a status of 405 (Not
Allowed)
I am afraid I might not understand the above solutions. Firstly, I am not sure about the btoa(username + ":" + password)
part. Are those special keywords or am I supposed to expose user:pass in those approaches?