PHP File Uploading


Through file uploading users can send files including images PDFs or documents from their browser to your web server using an HTML form and PHP script.

 


HTML Form for Uploading

Create an HTML form with:

  • method="POST"
  • enctype="multipart/form-data" (important!)
  • An input of type file

Example

<form action="upload.php" method="POST" enctype="multipart/form-data">
  Select file: <input type="file" name="myfile"><br><br>
  <input type="submit" value="Upload">
</form>    

PHP Script to Handle Upload (upload.php)

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_FILES["myfile"]) && $_FILES["myfile"]["error"] == 0) {
        $fileName = $_FILES["myfile"]["name"];
        $fileTmp = $_FILES["myfile"]["tmp_name"];
        $fileSize = $_FILES["myfile"]["size"];
        $fileType = $_FILES["myfile"]["type"];

        $uploadDir = "uploads/";
        $targetFile = $uploadDir . basename($fileName);

        // Move file from temporary location to desired folder
        if (move_uploaded_file($fileTmp, $targetFile)) {
            echo "File uploaded successfully: $fileName";
        } else {
            echo "Error uploading the file.";
        }
    } else {
        echo "No file selected or upload error.";
    }
}
?> 

Folder Structure

/project-folder
   ├── upload.php
   ├── form.html
   └── /uploads  ← Make sure this folder is writable 

Validation (File Type & Size)

<?php
$allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
$maxSize = 2 * 1024 * 1024; // 2MB

if (!in_array($fileType, $allowedTypes)) {
    echo "Only JPG, PNG, and PDF files are allowed.";
} elseif ($fileSize > $maxSize) {
    echo "File size exceeds 2MB limit.";
} else {
    move_uploaded_file($fileTmp, $targetFile);
    echo "File uploaded: $fileName";
}
?>

$_FILES Array

Key Description
$_FILES['myfile']['name'] Original name of file
$_FILES['myfile']['tmp_name'] Temporary server path
$_FILES['myfile']['type'] MIME type
$_FILES['myfile']['size'] File size in bytes
$_FILES['myfile']['error'] Upload error code



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.