Sometimes, we want to add file upload with PHP.
In this article, we’ll look at how to add file upload with PHP.
How to add file upload with PHP?
To add file upload with PHP, we can use fetch
on client side and then get the uploaded file from $_FILES
with PHP.
For instance, we write
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
to add a file input.
Then we write
async function saveFile() {
const formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch("/uploads", { method: "POST", body: formData });
}
to add the saveFile
function.
In it, we create a FormData
object and add an entry with key 'file'
into it.
Then we call fetch
with the URL and an object with the request method
and the body set to formData
.
Then in our PHP code, we add
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
to call get the file with $_FILES['file']
.
And we save the upload file with
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name'])
to save the uploaded file to the path we have in the 2nd argument.
Conclusion
To add file upload with PHP, we can use fetch
on client side and then get the uploaded file from $_FILES
with PHP.