How to Upload Files in PHP with Validation (Secure & Easy Guide)

File upload is one of the most important features in modern PHP websites — whether it’s profile photos, documents, or PDFs.

But many beginners upload files without validation, which can cause:

❌ Security risks
❌ Server crashes
❌ Invalid file formats

In this guide, you’ll learn:

✔ How PHP file upload works
✔ How to validate file size and type
✔ Secure file upload code

Let’s start 🚀


📂 Basic HTML File Upload Form

First create a simple form:

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit">Upload</button>
</form>

📥 Simple PHP File Upload Code

Create upload.php:

$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFile = $targetDir . $fileName;

move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile);

echo "File uploaded successfully!";

⚠ This works but is NOT secure.

Let’s make it safe 👇


✅ Validate File Type

Allow only images:

$allowedTypes = ["jpg", "jpeg", "png", "pdf"];
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

if(!in_array($fileType, $allowedTypes)){
    die("Only JPG, PNG & PDF files allowed!");
}

✅ Validate File Size

Limit to 2MB:

if($_FILES["file"]["size"] > 2000000){
    die("File too large! Max 2MB allowed.");
}

🔐 Secure File Upload (Final Code)

$targetDir = "uploads/";
$fileName = time() . "_" . basename($_FILES["file"]["name"]);
$targetFile = $targetDir . $fileName;

$allowedTypes = ["jpg","jpeg","png","pdf"];
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

if(!in_array($fileType, $allowedTypes)){
    die("Invalid file type!");
}

if($_FILES["file"]["size"] > 2000000){
    die("File too large!");
}

if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)){
    echo "File uploaded successfully!";
}else{
    echo "Upload failed!";
}

📌 Best Practices for PHP File Upload

✔ Always validate file type
✔ Limit file size
✔ Rename file to avoid overwrite
✔ Store uploads in separate folder


🎯 Final Words

Uploading files in PHP is easy — but uploading them securely is very important.

With proper validation, you can:

✅ Prevent hacking
✅ Avoid server overload
✅ Keep users safe

Bookmark this tutorial for future use 😊

Leave a Reply

Your email address will not be published. Required fields are marked *