0
0
PhpHow-ToBeginner · 4 min read

How to Validate File Upload in PHP: Syntax and Example

To validate file uploads in PHP, use the $_FILES superglobal to check the error status, file size, and MIME type before saving the file. Always verify $_FILES['input_name']['error'] === UPLOAD_ERR_OK and validate the file extension or MIME type to ensure security.
📐

Syntax

Use the $_FILES array to access uploaded file details. Check the error key for upload success, size for file size, and type or file extension for allowed formats.

  • $_FILES['input_name']['error']: Upload error code (0 means success)
  • $_FILES['input_name']['size']: File size in bytes
  • $_FILES['input_name']['name']: Original file name
  • $_FILES['input_name']['tmp_name']: Temporary file path
php
<?php
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $fileSize = $_FILES['file']['size'];
    $fileName = $_FILES['file']['name'];
    $fileTmp = $_FILES['file']['tmp_name'];
    // Validate size and type here
} else {
    // Handle upload error
}
?>
💻

Example

This example shows how to validate a file upload by checking for errors, limiting file size to 1MB, and allowing only PNG and JPEG images.

php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['file'])) {
        $file = $_FILES['file'];
        if ($file['error'] === UPLOAD_ERR_OK) {
            $allowedTypes = ['image/png', 'image/jpeg'];
            $maxSize = 1 * 1024 * 1024; // 1MB
            if ($file['size'] > $maxSize) {
                echo 'Error: File size exceeds 1MB.';
            } elseif (!in_array(mime_content_type($file['tmp_name']), $allowedTypes)) {
                echo 'Error: Only PNG and JPEG files are allowed.';
            } else {
                $uploadDir = 'uploads/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                $destination = $uploadDir . basename($file['name']);
                if (move_uploaded_file($file['tmp_name'], $destination)) {
                    echo 'File uploaded successfully.';
                } else {
                    echo 'Error: Failed to move uploaded file.';
                }
            }
        } else {
            echo 'Error: File upload error code ' . $file['error'];
        }
    } else {
        echo 'No file uploaded.';
    }
}
?>

<form method="post" enctype="multipart/form-data">
    <input type="file" name="file" required>
    <button type="submit">Upload</button>
</form>
Output
File uploaded successfully.
⚠️

Common Pitfalls

Common mistakes when validating file uploads include:

  • Not checking $_FILES['file']['error'] before processing the file.
  • Trusting the file extension alone instead of checking MIME type.
  • Not limiting file size, which can cause server overload.
  • Failing to use move_uploaded_file() to securely move the file.
  • Not sanitizing file names, risking overwriting or security issues.
php
<?php
// Wrong: trusting file extension only
$fileName = $_FILES['file']['name'];
$ext = pathinfo($fileName, PATHINFO_EXTENSION);
if ($ext === 'jpg' || $ext === 'png') {
    // This can be faked
}

// Right: check MIME type
$mime = mime_content_type($_FILES['file']['tmp_name']);
if ($mime === 'image/jpeg' || $mime === 'image/png') {
    // Safer validation
}
?>
📊

Quick Reference

Tips for validating file uploads in PHP:

  • Always check $_FILES['file']['error'] === UPLOAD_ERR_OK.
  • Limit file size with $_FILES['file']['size'].
  • Validate file type using mime_content_type() or finfo_file().
  • Use move_uploaded_file() to save files securely.
  • Sanitize file names to avoid security risks.

Key Takeaways

Always check the upload error code before processing the file.
Validate file size and MIME type to ensure only allowed files are accepted.
Use move_uploaded_file() to securely save uploaded files.
Never trust the file extension alone; always verify the file content type.
Sanitize file names to prevent overwriting and security issues.