Open In App

Write a Code To Upload A File in PHP?

Last Updated : 10 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

PHP makes it easy to upload files in web applications, whether it’s for images, documents, or other types of files. With its built-in functions, uploading files to the server becomes a simple task. However, it’s important to be cautious when allowing file uploads, as they can pose security risks. Always ensure that you implement proper security measures to prevent any unwanted issues.

Steps to Upload a file in PHP

Step 1: Configure The “php.ini” File

Before we start with the code, ensure that your PHP configuration allows file uploads. To do this, follow these steps:

  • Open your php.ini file (usually found in the PHP installation directory).
  • Search for file_uploads.
  • Make sure it’s set to On:
file_uploads = On

Step 2: Create the HTML Form for File Upload

To upload a file, we need an HTML form where users can select a file from their computer. The form must have the following attributes:

  • enctype=”multipart/form-data”: This tells the browser to send the file data as part of the HTTP request.
  • method=”POST”: To submit data securely.
HTML
<html>
<body>
    <form action="fileupload.php" method="post" enctype="multipart/form-data">
        Directory: <input type="text" name="dirname" id="dirname"><br>
        Select file to upload:
        <input type="file" name="fileToUpload" id="fileToUpload"><br>
        <input type="submit" value="Upload File" name="submit">
    </form>
</body>
</html>
  • The form allows users to specify a directory name where the file should be uploaded.
  • The <input type=”file”> field lets users select a file.
  • The form submits data to fileupload.php using the POST method.

Step 3: PHP Script to Handle File Upload

Now let’s look at the PHP script (fileupload.php) that will process the file upload. The script performs several important functions:

  1. Directory Handling: Verifies if the directory exists or creates a new one if necessary.
  2. File Extension Validation: Ensures that only valid file types are uploaded.
  3. File Size Validation: Limits the uploaded file size.
  4. File Existence Check: Prevents overwriting files with the same name.

1. Directory Handling

First, the script checks if the directory where the file will be uploaded exists. If not, it creates the directory.

PHP
<?php
if(!empty($_POST["dirname"])) {
    if(!is_dir($_POST["dirname"])) {
        mkdir($_POST["dirname"]);
        $uploadOk = 1;
    }
} else {
    echo "Specify the directory name...";
    $uploadOk = 0;
    exit;
}
?>
  • Check if Directory Exists: Verifies if the specified directory already exists.
  • Create Directory if Not Found: Creates the directory using mkdir() if it doesn’t exist.
  • Error Handling: Stops and shows an error if the directory is not specified.

2. File Extension Validation

Next, the script checks if the uploaded file has a valid extension. The allowed extensions are jpeg, jpg, png, pdf, and gif.

PHP
<?php
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$extensions = array("jpeg", "jpg", "png", "pdf", "gif");

if(in_array($imageFileType, $extensions) === true) {
    $uploadOk = 1;
} else {
    echo "No file selected or Invalid file extension...";
    $uploadOk = 0;
    exit;
}

?>
  • Get File Extension: Extracts the file extension to check if it’s valid.
  • Check Against Allowed Extensions: Compares the extension to an array of allowed types (e.g., jpeg, jpg, png).
  • Error Handling: Stops and shows an error if the extension is invalid.

3. File Size Validation

The script checks if the uploaded file is within the size limit. In this case, the size limit is set to 10MB.

PHP
<?php
if ($_FILES["fileToUpload"]["size"] > 10000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
    exit;
}

?>
  • Check File Size: Compares the file size with the set limit (10MB).
  • Stop if Too Large: Rejects the file if it exceeds the maximum allowed size.
  • Error Handling: Displays an error message if the file is too large.

4. File Existence Check

This ensures that files with the same name do not overwrite existing files in the target directory. It checks whether a file with the same name already exists in the specified directory.

PHP
<?php
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
    exit;
}
?>
  • Check If File Exists: Verifies if a file with the same name already exists in the target directory.
  • Prevent Overwriting: Stops the upload if a file with the same name is found.
  • Error Handling: Shows an error message if the file exists.

Complete code for fileupload.php

PHP
<?php

$target_dir = $_POST["dirname"] . "/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$extensions = array("jpeg", "jpg", "png", "pdf", "gif");

if (isset($_POST["submit"])) {

    // To check whether directory exist or not 
    if (!empty($_POST["dirname"])) {
        if (!is_dir($_POST["dirname"])) {
            mkdir($_POST["dirname"]);
            $uploadOk = 1;
        }
    } else {
        echo "Specify the directory name...";
        $uploadOk = 0;
        exit;
    }

    // To check extensions are correct or not 
    if (in_array($imageFileType, $extensions) === true) {
        $uploadOk = 1;
    } else {

        echo "No file selected or Invalid file extension...";
        $uploadOk = 0;
        exit;
    }
}
// Check if file already exists 
if (file_exists($target_file)) {

    echo "Sorry, file already exists.";
    $uploadOk = 0;
    exit;
}

// Check file size 
if ($_FILES["fileToUpload"]["size"] > 10000000) {

    echo "Sorry, your file is too large.";
    $uploadOk = 0;
    exit;
}

// Check if $uploadOk is set to 0 by an error 
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
} else {

    // If everything is ok, try to upload file 
    if (
        move_uploaded_file($_FILES["fileToUpload"]
        ["tmp_name"], $target_file)
    ) {
        echo "The file " . $_FILES["fileToUpload"]
        ["name"] . " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

Output

write the directory name and select the file

after uploading the file 

Optimizing File Upload Performance

  • Chunked Uploads: For large files, consider breaking the file into smaller chunks and uploading them sequentially. This reduces server load and increases reliability in case of connection interruptions.
  • Image Optimization: Before uploading, compress images to reduce file size without compromising quality. This can be done client-side using JavaScript or server-side with PHP libraries like GD or ImageMagick.
  • Use Asynchronous Uploading: Leverage AJAX or XMLHttpRequest for asynchronous file uploads to avoid blocking the main thread and improve user experience.

Best Practices

  • File Validation: Always validate file types, sizes, and extensions to prevent malicious files from being uploaded.
  • Security: Sanitize filenames and store files in a directory with restricted access to protect the server.
  • Efficient Handling: Use chunked uploads for large files, optimize images for size, and ensure real-time feedback during the upload process.
  • Database Integration: Optionally, store file metadata in a database for better tracking and management.
  • Error Handling: Implement clear error messages and checks for better user experience during the upload process.

Conclusion

File upload functionality is an essential feature in web applications. By ensuring proper validation, optimizing file sizes, and following best practices, we can improve both the performance and security of your file upload process. Implementing chunked uploads, image optimization, and secure storage will not only enhance user experience but also prevent potential server issue.



Similar Reads