PHP File Upload Handling

PHP File Upload Handling – Securely Upload Files ๐Ÿ“‚

Ever wondered how websites allow users to upload images, documents, or memes? PHP makes it easy to handle file uploads, but we need to do it securely!


๐Ÿ”น Creating a File Upload Form

To upload files in PHP, we need an HTML form with:

  • A file input field.
  • enctype="multipart/form-data" (to handle files).
  • A submit button.
<form action="upload.php" method="post" enctype="multipart/form-data">
    Select a file to upload:
    <input type="file" name="uploadedFile">
    <input type="submit" value="Upload">
</form>

๐Ÿ”น Handling File Uploads in PHP

When a file is uploaded, it is stored in $_FILES. We use move_uploaded_file() to move it to a permanent location.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["uploadedFile"])) {
    $targetDirectory = "uploads/"; // Folder to store uploaded files
    $targetFile = $targetDirectory . basename($_FILES["uploadedFile"]["name"]);

    if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $targetFile)) {
        echo "File uploaded successfully! ๐Ÿš€";
    } else {
        echo "Error uploading the file! โŒ";
    }
}
?>

Try It Now


๐Ÿ”น File Upload Security Tips

Uploading files without security can be dangerous! Here are some best practices:

  • โœ… Allow only specific file types (e.g., images, PDFs).
  • โœ… Set a file size limit to prevent large uploads.
  • โœ… Store files in a non-public folder to avoid direct access.
  • โœ… Rename files before saving to prevent overwriting.

๐Ÿ“ Example: Secure File Upload

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["uploadedFile"])) {
    $targetDirectory = "uploads/";
    $fileName = basename($_FILES["uploadedFile"]["name"]);
    $targetFile = $targetDirectory . $fileName;
    $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

    // Allowed file types
    $allowedTypes = array("jpg", "png", "gif", "pdf");

    // Check file type
    if (!in_array($fileType, $allowedTypes)) {
        echo "Only JPG, PNG, GIF, and PDF files are allowed!";
        exit;
    }

    // Check file size (limit: 2MB)
    if ($_FILES["uploadedFile"]["size"] > 2 * 1024 * 1024) {
        echo "File is too large!";
        exit;
    }

    // Move file securely
    if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $targetFile)) {
        echo "File uploaded securely! ๐ŸŽฏ";
    } else {
        echo "Error uploading the file!";
    }
}
?>

Try It Now


๐ŸŽฏ Key Takeaways

  • $_FILES stores uploaded file details.
  • move_uploaded_file() moves the file to a safe location.
  • Always validate file types and sizes before saving.
  • Store sensitive files in a non-public directory.

๐Ÿ“ Practice Time!

Try uploading different file types and test the security features. What happens when you upload an unsupported file? ๐Ÿค”