PHP File Upload

Handling file uploads from users

📤 What is File Upload?

PHP file upload allows users to send files from their computer to your server through web forms. You can upload images, documents, videos, and other files while controlling size, type, and security.


<?php
// Basic file upload handling
if(isset($_FILES['myfile'])) {
    move_uploaded_file($_FILES['myfile']['tmp_name'], "uploads/file.jpg");
}
?>
                                    

File Upload Components

📋

HTML Form

Create a form with enctype="multipart/form-data" to enable file uploads. The input type must be "file" for selecting files from user's device.

<form method="post" enctype="multipart/form-data">
    <input type="file" name="myfile">
    <input type="submit">
</form>
📦

$_FILES Array

PHP stores uploaded file information in the $_FILES superglobal array containing name, type, size, temporary location, and error status.

<?php
$name = $_FILES['myfile']['name'];
$size = $_FILES['myfile']['size'];
?>
🔒

Validation

Check file size, type, and extension before accepting uploads. Prevent malicious files and ensure only allowed formats are uploaded to your server.

<?php
if($_FILES['myfile']['size'] > 1000000) {
    echo "File too large!";
}
?>
💾

move_uploaded_file()

Move the uploaded file from temporary location to permanent destination. This function ensures the file was actually uploaded through HTTP POST.

<?php
move_uploaded_file($tmp, "uploads/file.jpg");
?>

🔹 Creating Upload Form

HTML form for file uploads:

<!DOCTYPE html>
<html>
<body>

<h2>Upload File</h2>

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

</body>
</html>

Important Form Attributes:

  • method="post" - Must use POST method
  • enctype="multipart/form-data" - Required for file uploads
  • type="file" - Creates file selection input

🔹 Basic Upload Script

Simple PHP script to handle file uploads:

<?php
// upload.php

if(isset($_POST['submit'])) {
    $targetDir = "uploads/";
    $targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
    
    // Try to upload file
    if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
        echo "The file " . basename($_FILES["fileToUpload"]["name"]) . " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

Output (on success):

The file photo.jpg has been uploaded.

🔹 Understanding $_FILES Array

The $_FILES array contains important information:

<?php
// Display file information
print_r($_FILES['fileToUpload']);

/* Output:
Array (
    [name] => photo.jpg          // Original filename
    [type] => image/jpeg         // MIME type
    [tmp_name] => /tmp/php123    // Temporary location
    [error] => 0                 // Error code (0 = no error)
    [size] => 245678             // File size in bytes
)
*/

// Access individual values
$fileName = $_FILES['fileToUpload']['name'];
$fileSize = $_FILES['fileToUpload']['size'];
$fileTmp = $_FILES['fileToUpload']['tmp_name'];
$fileType = $_FILES['fileToUpload']['type'];
$fileError = $_FILES['fileToUpload']['error'];
?>

🔹 File Upload with Validation

Add security checks before accepting uploads:

<?php
if(isset($_POST['submit'])) {
    $targetDir = "uploads/";
    $fileName = basename($_FILES["fileToUpload"]["name"]);
    $targetFile = $targetDir . $fileName;
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
    
    // Check if file already exists
    if(file_exists($targetFile)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    
    // Check file size (limit to 5MB)
    if($_FILES["fileToUpload"]["size"] > 5000000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    
    // Allow only certain file formats
    $allowed = ["jpg", "jpeg", "png", "gif"];
    if(!in_array($imageFileType, $allowed)) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    
    // Check if $uploadOk is set to 0 by an error
    if($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    } else {
        if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
            echo "The file " . $fileName . " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}
?>

🔹 Validating Image Files

Check if uploaded file is a real image:

<?php
if(isset($_POST['submit'])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
?>

🔹 Generating Unique Filenames

Prevent filename conflicts by creating unique names:

<?php
$originalName = $_FILES["fileToUpload"]["name"];
$extension = pathinfo($originalName, PATHINFO_EXTENSION);

// Method 1: Add timestamp
$newName = time() . "_" . $originalName;

// Method 2: Generate random name
$newName = uniqid() . "." . $extension;

// Method 3: Use MD5 hash
$newName = md5($originalName . time()) . "." . $extension;

$targetFile = "uploads/" . $newName;
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile);

echo "File uploaded as: " . $newName;
?>

🔹 Multiple File Upload

Upload multiple files at once:

🔸 HTML Form

<form action="upload_multiple.php" method="post" enctype="multipart/form-data">
    Select files:
    <input type="file" name="files[]" multiple>
    <input type="submit" value="Upload Files">
</form>

🔸 PHP Handler

<?php
if(isset($_POST['submit'])) {
    $totalFiles = count($_FILES['files']['name']);
    
    for($i = 0; $i < $totalFiles; $i++) {
        $fileName = $_FILES['files']['name'][$i];
        $fileTmp = $_FILES['files']['tmp_name'][$i];
        
        $targetFile = "uploads/" . $fileName;
        
        if(move_uploaded_file($fileTmp, $targetFile)) {
            echo "File $fileName uploaded successfully.<br>";
        } else {
            echo "Error uploading $fileName.<br>";
        }
    }
}
?>

🔹 Complete Upload Example

Full featured upload script with all validations:

<?php
if(isset($_POST['submit'])) {
    $targetDir = "uploads/";
    $fileName = basename($_FILES["file"]["name"]);
    $targetFile = $targetDir . $fileName;
    $uploadOk = 1;
    $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
    
    // Check if image
    $check = getimagesize($_FILES["file"]["tmp_name"]);
    if($check === false) {
        echo "File is not an image.<br>";
        $uploadOk = 0;
    }
    
    // Check file size (5MB max)
    if($_FILES["file"]["size"] > 5000000) {
        echo "File is too large.<br>";
        $uploadOk = 0;
    }
    
    // Allow certain formats
    if(!in_array($fileType, ["jpg", "jpeg", "png", "gif"])) {
        echo "Only JPG, JPEG, PNG & GIF allowed.<br>";
        $uploadOk = 0;
    }
    
    // Upload file
    if($uploadOk == 1) {
        // Generate unique name
        $newName = uniqid() . "." . $fileType;
        $targetFile = $targetDir . $newName;
        
        if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
            echo "File uploaded successfully as: " . $newName;
        } else {
            echo "Error uploading file.";
        }
    }
}
?>

🧠 Test Your Knowledge

Which function moves an uploaded file to a permanent location?