PHP File Upload – Simple and Secure Guide with Code Example
Create an HTML Form
<form action="upload.php" method="POST" enctype="multipart/form-data">
    <label for="file">Choose a file:</label>
    <input type="file" name="file" id="file">
    <input type="submit" value="Upload File">
</form>
- enctype="multipart/form-data"is required for file uploads.
- The inputelement withtype="file"allows users to select a file.
Handle File Upload in PHP (upload.php)
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $targetDir = "uploads/"; // Directory to store the uploaded file
    $fileName = basename($_FILES["file"]["name"]);
    $targetFilePath = $targetDir . $fileName;
    $fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));
    // Allowed file types
    $allowedTypes = array("jpg", "png", "jpeg", "gif", "pdf");
    // Validate file type
    if (in_array($fileType, $allowedTypes)) {
        // Check for file upload errors
        if ($_FILES["file"]["error"] === UPLOAD_ERR_OK) {
            // Move the file to the target directory
            if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)) {
                echo "File uploaded successfully: $fileName";
            } else {
                echo "Error uploading file.";
            }
        } else {
            echo "Error during file upload.";
        }
    } else {
        echo "Invalid file type. Only JPG, PNG, JPEG, GIF, and PDF files are allowed.";
    }
}
Create the "uploads" Directory
- In the root of your project, create a folder called uploads.
- Set the write permissions so that PHP can save the uploaded files.
File Upload Validation
- Allow only specific file types (e.g., JPG, PNG, PDF)
- Limit file size (e.g., max 2MB)
- Protect against file overwriting
Add File Size Restriction (Optional)
$maxFileSize = 2 * 1024 * 1024; // 2 MB
if ($_FILES["file"]["size"] > $maxFileSize) {
    echo "File size exceeds the 2MB limit.";
}
Complete PHP File Upload Code
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $targetDir = "uploads/";
    $fileName = basename($_FILES["file"]["name"]);
    $targetFilePath = $targetDir . $fileName;
    $fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION));
    $allowedTypes = array("jpg", "png", "jpeg", "gif", "pdf");
    $maxFileSize = 2 * 1024 * 1024; // 2 MB
    if (in_array($fileType, $allowedTypes)) {
        if ($_FILES["file"]["size"] <= $maxFileSize) {
            if ($_FILES["file"]["error"] === UPLOAD_ERR_OK) {
                if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)) {
                    echo "File uploaded successfully: $fileName";
                } else {
                    echo "Error uploading file.";
                }
            } else {
                echo "Error during file upload.";
            }
        } else {
            echo "File size exceeds the 2MB limit.";
        }
    } else {
        echo "Invalid file type. Only JPG, PNG, JPEG, GIF, and PDF files are allowed.";
    }
}
?>
Output Example
File uploaded successfully: example.jpg
Invalid file type
File size exceeds the limit
Best Practices for PHP File Upload
- Sanitize file names to prevent security vulnerabilities
- Restrict file types and size
- Use unique file names to avoid overwriting
