Creating a Secure Image Upload Script in PHP

Image uploads are a common feature in many web applications. They allow users to upload and share images on a website, and are often used for things like profile pictures, product images, and other types of content. In this blog post, we will go over the process of creating an image upload script in PHP.

Before we begin, it’s important to note that there are many different ways to handle image uploads in PHP, and this post will cover one basic example. Additionally, it’s important to keep security in mind when handling image uploads. Proper validation and sanitation of the uploaded files is crucial to prevent malicious file uploads that can lead to security vulnerabilities.

The first step in creating an image upload script is to create an HTML form that will allow the user to select and upload the image. The form should have a file input field, and the form’s method should be set to “post” and the enctype should be set to “multipart/form-data”.

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

The next step is to create the PHP script that will handle the image upload. The script should check if the form has been submitted, get the file information, check the file type and size, generate a new file name, move the file to the new location, and display a success or error message depending on the result.


// Check if the form has been submitted
    // Get the file information
    $file = $_FILES['image'];

    // Get the file name, temporary location, and size
    $fileName = $file['name'];
    $fileTmp = $file['tmp_name'];
    $fileSize = $file['size'];

    // Get the file type
    $fileType = $file['type'];

    // Allowed file types
    $allowedTypes = array("image/jpeg", "image/png", "image/gif");

    // Check if the file type is allowed
    if(in_array($fileType, $allowedTypes)){
        // Check if the file size is within the allowed limit
        if($fileSize <= 2000000){
            // Generate a new file name
            $newFileName = time() . $fileName;

            // Set the new file path
            $newFilePath = "uploads/" . $newFileName;

            // Move the file to the new location
            move_uploaded_file($fileTmp, $newFilePath);

            // Show a success message
            echo "The file has been uploaded successfully!";
            // Show an error message
            echo "The file size is too large. Maximum size is 2MB.";
        // Show an error message
        echo "Invalid file type. Only JPG, PNG, and GIF are allowed.";


In this example, the script is set to only allow JPG, PNG, and GIF file types, and the maximum file size is 2MB. You can adjust these settings according to your needs.

It’s important to validate the uploaded files before storing them on the server to prevent