HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP $_FILES

The $_FILES superglobal is an associative array of items uploaded to the current script via the HTTP POST method. It allows you to access file metadata and move the files to a permanent location on your server.


1. The HTML Requirement

To upload files, your HTML <form> MUST have the enctype="multipart/form-data" attribute. Without it, file data will not be sent.

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

2. Structure of $_FILES

When a file is uploaded, PHP populates the $_FILES array with the following keys:

Key Description
name The original name of the file on the user's computer.
type The mime type of the file (e.g., "image/jpeg").
tmp_name The temporary path where the file is stored on the server.
error The error code associated with this file upload.
size The size of the uploaded file in bytes.

3. Moving the File

By default, uploaded files are stored in a temporary directory on the server. To keep them, you must move them using move_uploaded_file().

<?php
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
?>
Temporary Nature: If you don't move the file using move_uploaded_file(), the file will be deleted from the temporary directory as soon as the PHP script finishes executing.
Security Alert: File uploads are a major security risk. Users could upload malicious scripts (.php, .js). Always check the file extension and file type before allowing an upload.
Pro Tip: Use getimagesize() to verify if an uploaded file is actually an image and not a fake script disguised with an image extension.

Key Takeaways

  • Always use enctype="multipart/form-data" in the form.
  • The $_FILES array contains 5 essential keys for metadata.
  • Files are initially stored in a temporary location (tmp_name).
  • Use move_uploaded_file() to persist the file.
  • Strictly validate file types and sizes to keep your server safe.