Example PHP File Upload Code

Example PHP File Upload Code

·

2 min read

File uploads in PHP are a common feature in web applications, allowing users to upload files like images, documents, etc., to the server. Here's a basic example of handling file uploads in PHP:

Create the HTML form:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Upload</title>
</head>
<body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <label for="file">Choose a file:</label>
        <input type="file" name="file" id="file">
        <button type="submit" name="submit">Upload</button>
    </form>
</body>
</html>

Create the PHP script (upload.php) to handle the file upload:

<?php
if (isset($_POST['submit'])) {
    $targetDirectory = "uploads/";
    $targetFile = $targetDirectory . basename($_FILES['file']['name']);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

    // Check if the file already exists
    if (file_exists($targetFile)) {
        echo "Sorry, the file already exists.";
        $uploadOk = 0;
    }

    // Check file size (adjust as needed)
    if ($_FILES['file']['size'] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }

    // Allow only certain file formats (you can customize this list)
    $allowedFormats = array("jpg", "jpeg", "png", "gif");
    if (!in_array($imageFileType, $allowedFormats)) {
        echo "Sorry, only JPG, JPEG, PNG, and GIF files are allowed.";
        $uploadOk = 0;
    }

    // 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['file']['tmp_name'], $targetFile)) {
            echo "The file " . basename($_FILES['file']['name']) . " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}
?>

This script performs several checks, such as file size, format, and existence, before attempting to upload the file. It also provides feedback on the success or failure of the upload.

Ensure the "uploads" directory exists:

Create a directory named "uploads" in the same directory as your PHP script. This is where the uploaded files will be stored.

Set appropriate permissions:

Make sure the "uploads" directory has the necessary permissions to allow file uploads. The web server needs to write permissions to this directory.

Note: This example provides basic functionality and security checks. Depending on your specific use case, you may need to enhance security measures, such as validating file types more thoroughly, preventing malicious uploads, and securing the upload directory.