The problem
I'm trying to make an AJAX file uploader with Php and Javascript. The problem I'm having is that in my upload.php script where I'm trying to use the move_uploaded_file
function, the $_FILES
array is always empty.
Here's what I've tried thus far
- Checked
file_uploads = On
in/etc/php/7.2/apache2/php.ini
- Checked the current working directory of
uploader.php
andupload.php
- Checked the file permissions of
uploads
- Changed the
uploads_tmp_dir
in/etc/php/7.2/apache2/php.ini
The MWE
Html in uploader.php:
<form class="form" id="upload_form">
<input type="file" name="file_to_upload" id="file_to_upload"><br>
<input class="button" type="submit" value="Upload">
</form>
Javascript in uploader.php:
<script>
var upload_form = document.getElementById('upload_form');
var file_to_upload = document.getElementById('file_to_upload');
upload_form.addEventListener("submit", upload_file);
function upload_file (e) {
e.preventDefault();
var xhr = new XMLHttpRequest()
xhr.open("POST", "upload.php");
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send(new FormData(upload_form));
}
</script>
upload.php:
<?php
//$target_path = "uploads/".basename($_FILES["file_to_upload"]["name"]);
$uploaded_file = $_FILES['file_to_upload']['tmp_name'];
var_dump($_FILES); // This is always array(0) { }
if(file_exists($uploadedFile)) {
echo "file uploaded to temp dir";
} else {
echo "file upload failed"; // This is always the outcome
}
//move_uploaded_file($_FILES["file_to_upload"]["tmp_name"], $target_path);
?>