PHP File Upload
PHP handles file uploads through the $_FILES superglobal, which is populated when an HTML form uses enctype="multipart/form-data" and includes a file input field.
Uploaded files are temporarily stored on the server, and you must use move_uploaded_file() to move them to a permanent location. Always validate file type and size before accepting an upload to keep your application secure.
<form enctype="multipart/form-data" method="post">
<input type="file" name="photo">
</form>The upload form
The form must include enctype="multipart/form-data" and method="post" for file uploads to work correctly, along with an <input type="file"> element.
Processing the upload
$_FILES["fieldname"] contains details like tmp_name, name, size and error. move_uploaded_file() moves the temporary file to a permanent destination folder.
<?php
// Assuming a valid upload named "photo"
$target = "uploads/" . basename($_FILES["photo"]["name"]);
if (move_uploaded_file($_FILES["photo"]["tmp_name"], $target)) {
echo "Upload successful";
}
?>Upload successfulmove_uploaded_file() moves the temporary uploaded file to the uploads folder.
<?php
$allowed = ["jpg", "png"];
$ext = strtolower(pathinfo($_FILES["photo"]["name"], PATHINFO_EXTENSION));
echo in_array($ext, $allowed) ? "Allowed type" : "Invalid type";
?>Allowed typeChecking the file extension against an allow-list helps prevent unwanted file types from being uploaded.
Key points
- $_FILES holds information about uploaded files.
- The form needs enctype="multipart/form-data" to support file uploads.
- move_uploaded_file() saves the uploaded file to a permanent location.
- Always validate file type and size before accepting an upload.
