The $_FILES superglobal in PHP is used to collect information about uploaded files. It works together with move_uploaded_file() to securely transfer files from a temporary upload location to a permanent directory on the server.
$_FILES stores name, size, type, and temporary pathmove_uploaded_file() ensures secure file movementUploaded files are accessed using $_FILES['inputName']. The temporary file must be moved using move_uploaded_file(tmp, destination) for permanent storage.
// HTML form for uploading a single file
<form action="upload.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" name="fileToUpload">
<input type="submit" name="submit" value="Upload File">
</form>
// PHP script to validate and upload a file
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Validate image file
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if ($check === false) { $uploadOk = 0; }
// Validate file size
if ($_FILES["fileToUpload"]["size"] > 500000) { $uploadOk = 0; }
// Validate file format
if (!in_array($fileType, ["jpg","jpeg","png","gif"])) { $uploadOk = 0; }
// Move file if all checks pass
if ($uploadOk == 1) {
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
}
}
?>
If all validations pass, the file is moved to the uploads/ folder. Otherwise, the upload is rejected to maintain security.
Try selecting different file types and sizes to observe how validation rules affect the upload process.