'HTML PHP File Upload :: Uploaded File Doesn't Appear On Server
I'm following this tutorial, trying to set up a simple website where a user can upload a file. I should say that I'm really new to HTML and PHP.
So my webserver is Apache2, running on Ubuntu 16.04. In my server's /var/www/html/ directory, I have:
me@myServer:/var/www/html$ ls -l
total 36
-rw-r--r-- 1 ph9821 ph9821 1032 Feb 18 12:23 index.html
-rwxr-xr-x 1 ph9821 ph9821 480 Feb 18 12:18 uploader.php
drwxr-xr-x 2 ph9821 ph9821 4096 Feb 18 12:16 uploads
me@myServer:/var/www/html$
My test website is terribly boring:
The index.html describes my two buttons, one to upload a file from the client's machine:
<!DOCTYPE html>
<html>
<body>
<h2>DIY HTML5 File Uploader</h2>
<input type="file" name="file_to_upload" id="file_to_upload">
<hr>
<input type="button" value="Upload To Server" id="upload_file_button">
<script>
document.getElementById('file_to_upload').addEventListener('change', (event) => {
window.selectedFile = event.target.files[0];
});
document.getElementById('upload_file_button').addEventListener('click', (event) => {
uploadFile(window.selectedFile);
});
function uploadFile(file) {
var formData = new FormData();
formData.append('file_to_upload', file);
var ajax = new XMLHttpRequest();
ajax.open('POST', 'uploader.php');
ajax.send(formData);
}
</script>
</body>
</html>
The HTML references uploader.php, which is:
<?php
$file_name = $_FILES["file_to_upload"]["name"];
$file_temp_location = $_FILES["file_to_upload"]["tmp_name"];
if (!$file_temp_location) {
echo "ERROR: No file has been selected";
exit();
}
if(move_uploaded_file($file_temp_location, "/var/www/html/uploads/$file_name")){
echo "$file_name upload is complete";
} else {
echo "A server was unable to move the file";
}
?>
The PHP code should save the uploaded file in my uploads directory, indicated above. Sadly, when you click "Choose File", select a file on your client machine, and then click "Upload to Server", the file does not appear in that directory. In fact, it doesn't appear anywhere. After uploading, I can't spot my target filename when using the Unix find command. The uploaded file simply isn't saved on the server.
I'm missing something. I can read through the above code and generally understand what each line is doing. But I just don't have the experience to spot where I'm going wrong. Can anyone offer any advice? Thank you.
Solution 1:[1]
try changing your move_uploaded_file() dir and provide a path relative to the php file
if(move_uploaded_file($file_temp_location, "uploads/$file_name")){
echo "$file_name upload is complete";
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | xrayian |

