← Back to Chapters

PHP $_FILES & move_uploaded_file()

? PHP $_FILES & move_uploaded_file()

? Quick Overview

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.

? Key Concepts

  • $_FILES stores name, size, type, and temporary path
  • Files are first uploaded to a temporary directory
  • move_uploaded_file() ensures secure file movement

? Syntax / Theory

Uploaded files are accessed using $_FILES['inputName']. The temporary file must be moved using move_uploaded_file(tmp, destination) for permanent storage.

? File Upload Form

? View Code Example
// 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>

? Handling Upload in PHP

? View Code Example
// 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);
}
}
?>

? Live Output / Explanation

If all validations pass, the file is moved to the uploads/ folder. Otherwise, the upload is rejected to maintain security.

? Interactive Example

Try selecting different file types and sizes to observe how validation rules affect the upload process.

? Use Cases

  • User profile image uploads
  • Document submission systems
  • Media upload features

✅ Tips & Best Practices

  • Always validate file type and size
  • Use unique filenames to avoid overwriting
  • Store uploads outside public directories

? Try It Yourself

  • Allow only PDF uploads
  • Add file renaming logic
  • Enable multiple file uploads