"I am Saqib Jahangir. A passionate vlogger, software engineer, trainer and avid traveler with a deep love for exploring the hidden gems of our beautiful planet. With a strong foundation in Application Development, Application Architecture & Database Design and Product Management, I bring over a decade of hands-on experience building secure, scalable, and resilient web applications for a diverse range of industries."


Click Above to BOOK HOTEL NOW!

Uploading Files with PHP

 

Uploading files is one of the most useful features in web development. PHP makes it simple to handle file uploads securely and efficiently. For example, when you upload a profile picture or a PDF document, PHP processes the file and stores it on the server.


Basic Steps for File Upload in PHP

  1. Create an HTML form – where the user selects a file.
  2. Handle the file in PHP – using the $_FILES superglobal.
  3. Save the file – to a desired folder on the server.
  4. Apply validation – check file type, size, and errors.

📝 Example: Simple File Upload

HTML Form

<html>

<body>

    <h2>Upload a File</h2>

    <form action="upload.php" method="post" enctype="multipart/form-data">

        <input type="file" name="myfile">

        <input type="submit" value="Upload">

    </form>

</body>

</html>

PHP Script (upload.php)

<?php

if (isset($_FILES['myfile'])) {

    $targetDir = "uploads/"; // Folder to store files

    $targetFile = $targetDir . basename($_FILES["myfile"]["name"]);

 

    if (move_uploaded_file($_FILES["myfile"]["tmp_name"], $targetFile)) {

        echo "The file ". basename($_FILES["myfile"]["name"]). " has been uploaded.";

    } else {

        echo "Sorry, there was an error uploading your file.";

    }

}

?>

This code uploads the file to the uploads/ directory.


🔒 Validating the Upload

It’s important to validate uploads for security and performance reasons.

1. Check File Size

if ($_FILES["myfile"]["size"] > 2000000) { // 2MB limit

    echo "Sorry, your file is too large.";

}

2. Allow Only Specific File Types

$allowedTypes = ["jpg", "png", "jpeg", "gif", "pdf"];

$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

 

if (!in_array($fileType, $allowedTypes)) {

    echo "Only JPG, PNG, GIF & PDF files are allowed.";

}

3. Check for Upload Errors

if ($_FILES['myfile']['error'] !== 0) {

    echo "Error uploading file. Code: " . $_FILES['myfile']['error'];

}


📌 Complete Example with Validation

<?php

if (isset($_FILES["myfile"])) {

    $targetDir = "uploads/";

    $targetFile = $targetDir . basename($_FILES["myfile"]["name"]);

    $uploadOk = 1;

    $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

 

    // Check file size

    if ($_FILES["myfile"]["size"] > 2000000) {

        echo "File is too large.";

        $uploadOk = 0;

    }

 

    // Allow specific file formats

    $allowedTypes = ["jpg", "png", "jpeg", "gif", "pdf"];

    if (!in_array($fileType, $allowedTypes)) {

        echo "Only JPG, PNG, GIF & PDF files are allowed.";

        $uploadOk = 0;

    }

 

    // Upload if everything is fine

    if ($uploadOk == 1) {

        if (move_uploaded_file($_FILES["myfile"]["tmp_name"], $targetFile)) {

            echo "The file ". basename($_FILES["myfile"]["name"]). " has been uploaded.";

        } else {

            echo "Error uploading your file.";

        }

    }

}

?>


🎯 Best Practices for File Upload in PHP

  • Always validate file type and size.
  • Rename uploaded files to avoid conflicts (uniqid() or timestamp).
  • Store sensitive files outside the public folder.
  • Never trust file extensions alone (check MIME type if possible).
  • Use HTTPS to protect uploads.

 

Click Below to Shop Now at AMAZON

Popular Posts

Operators (Arithmetic, Comparison, Logical)

Functions (Built-in & User-defined)