PHP Tutorial

PHP Flow Control

PHP Functions

PHP String

PHP Array

PHP Date Time

PHP Object Oriented

Regular Expression

PHP Cookie & Session

PHP Error & Exception handling

MySQL in PHP

PHP File Directory

PHP Image Processing

PHP File Upload

Uploading files in PHP is a common task, especially for web applications that require users to upload images, documents, and other types of files. Here's a simple tutorial on how to handle file uploads in PHP:

HTML Form:

Firstly, you need to create an HTML form that includes an input field of type file. The form's enctype attribute must be set to "multipart/form-data" which ensures the file data is sent correctly.

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select file to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload File" name="submit">
</form>

PHP Script (upload.php):

In your PHP script, you can access the uploaded file through the $_FILES superglobal array. Here's a simple script that handles the file upload:

<?php
    $target_dir = "uploads/"; // Specify the directory where file is going to be placed
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); // Specify the path of the file to be uploaded

    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        exit;
    }

    // Attempt to move the uploaded file to your desired location
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
?>

This script checks whether a file with the same name already exists in the target directory. If it doesn't, it attempts to move the uploaded file to the target directory using the move_uploaded_file() function.

The $_FILES["fileToUpload"]["tmp_name"] contains the temporary location of the uploaded file on the server. The move_uploaded_file() function moves the file from this temporary location to the specified target location.

Security Note: File upload operations can pose significant security risks to your application if not handled carefully. You should always validate and sanitize the uploaded file, such as checking the file's MIME type, to ensure that it's the type of file you expect. Also, file permissions and ownership should be set properly to prevent unauthorized access. In a production environment, more complex validation and sanitization would be required than what is shown in this basic tutorial.

  1. Handling file uploads in PHP: Use the $_FILES superglobal to handle file uploads in PHP:

    <?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $targetDir = 'uploads/';
        $targetFile = $targetDir . basename($_FILES['file']['name']);
    
        if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
            echo "File uploaded successfully.";
        } else {
            echo "Error uploading file.";
        }
    }
    ?>
    
    <form method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="Upload">
    </form>
    
  2. PHP file upload example code: A simple example of file upload in PHP:

    <?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $targetDir = 'uploads/';
        $targetFile = $targetDir . basename($_FILES['file']['name']);
    
        if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
            echo "File uploaded successfully.";
        } else {
            echo "Error uploading file.";
        }
    }
    ?>
    
    <form method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="Upload">
    </form>
    
  3. Maximum file size limit in PHP file upload: Set a maximum file size limit for file uploads in PHP using upload_max_filesize and post_max_size directives in PHP configuration:

    <?php
    echo "Maximum File Size: " . ini_get('upload_max_filesize');
    ?>
    
  4. PHP file upload and validation: Validate file type and size before uploading in PHP:

    <?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $allowedExtensions = ['jpg', 'jpeg', 'png'];
        $maxFileSize = 5 * 1024 * 1024; // 5 MB
    
        $targetDir = 'uploads/';
        $targetFile = $targetDir . basename($_FILES['file']['name']);
        $fileExtension = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
    
        if (in_array($fileExtension, $allowedExtensions) && $_FILES['file']['size'] <= $maxFileSize) {
            if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
                echo "File uploaded successfully.";
            } else {
                echo "Error uploading file.";
            }
        } else {
            echo "Invalid file type or size.";
        }
    }
    ?>
    
    <form method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="Upload">
    </form>
    
  5. Uploading multiple files in PHP: Enable multiple file uploads in PHP:

    <?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $targetDir = 'uploads/';
    
        foreach ($_FILES['files']['tmp_name'] as $key => $tmpName) {
            $targetFile = $targetDir . basename($_FILES['files']['name'][$key]);
    
            if (move_uploaded_file($tmpName, $targetFile)) {
                echo "File uploaded successfully.";
            } else {
                echo "Error uploading file.";
            }
        }
    }
    ?>
    
    <form method="post" enctype="multipart/form-data">
        <input type="file" name="files[]" multiple>
        <input type="submit" value="Upload">
    </form>