Logo

How to Upload an Image in PHP?

How to Upload an Image in PHP?

How to Upload an Image in PHP?

Hello, developers! Uploading images is a common task in web development. In this article, we will explore different methods to upload images in PHP.
We will cover basic to advanced techniques, ensuring you have all the tools you need for your projects. Let’s get started!

Method 1 : Basic Image Upload

The simplest way to upload an image in PHP involves using an HTML form and handling the file upload with PHP.

1.) HTML Form

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

				
			

2.) PHP Script (upload.php)

				
					<?php

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

    // Check if image file is an actual image or fake image
    $check = getimagesize($_FILES["file"]["tmp_name"]);
    if ($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }

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

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

    // Allow certain file formats
    if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
        echo "Sorry, only JPG, JPEG, PNG & 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.";
    // If everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
            echo "The file " . htmlspecialchars(basename($_FILES["file"]["name"])) . " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
}

?>

				
			

In this example, we create an HTML form to select an image file and a PHP script to handle the file upload. The PHP script includes checks for file size, file type, and whether the file already exists.

Method 2 : Uploading Images with Validation and Error Handling

The simplest way to upload an image in PHP involves using an HTML form and handling the file upload with PHP.

1.) HTML Form (Same as in Method 1)

2.) PHP Script (upload.php)

				
					<?php

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

    // Check if image file is an actual image or fake image
    $check = getimagesize($_FILES["file"]["tmp_name"]);
    if ($check === false) {
        $errors[] = "File is not an image.";
        $uploadOk = 0;
    }

    // Check if file already exists
    if (file_exists($targetFile)) {
        $errors[] = "File already exists.";
        $uploadOk = 0;
    }

    // Check file size
    if ($_FILES["file"]["size"] > 500000) {
        $errors[] = "Your file is too large.";
        $uploadOk = 0;
    }

    // Allow certain file formats
    $allowedFormats = ["jpg", "jpeg", "png", "gif"];
    if (!in_array($imageFileType, $allowedFormats)) {
        $errors[] = "Only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        foreach ($errors as $error) {
            echo $error . "<br>";
        }
        echo "Your file was not uploaded.";
    } else {
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
            echo "The file " . htmlspecialchars(basename($_FILES["file"]["name"])) . " has been uploaded.";
        } else {
            echo "There was an error uploading your file.";
        }
    }
}

?>

				
			

In this enhanced version, we collect errors in an array and display them all at once, improving user feedback and validation.

Method 3 : Using PHP and AJAX for Image Upload

For a smoother user experience, you can use AJAX to upload images without refreshing the page.

1.) HTML Form

				
					<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Image with AJAX</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <form id="uploadForm" enctype="multipart/form-data">
        <label for="file">Choose Image:</label>
        <input type="file" name="file" id="file">
        <input type="submit" value="Upload">
    </form>

    <div id="uploadStatus"></div>

    <script>
        $(document).ready(function () {
            $('#uploadForm').on('submit', function (e) {
                e.preventDefault();
                $.ajax({
                    url: 'upload_ajax.php',
                    type: 'POST',
                    data: new FormData(this),
                    processData: false,
                    contentType: false,
                    success: function (response) {
                        $('#uploadStatus').html(response);
                    },
                    error: function () {
                        $('#uploadStatus').html('Error uploading file.');
                    }
                });
            });
        });
    </script>
</body>
</html>

				
			

2.) PHP Script (upload_ajax.php)

				
					<?php

if (isset($_FILES["file"]["name"])) {
    $targetDir = "uploads/";
    $targetFile = $targetDir . basename($_FILES["file"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
    $response = "";

    // Check if image file is an actual image or fake image
    $check = getimagesize($_FILES["file"]["tmp_name"]);
    if ($check === false) {
        $response = "File is not an image.";
        $uploadOk = 0;
    }

    // Check if file already exists
    if (file_exists($targetFile)) {
        $response = "File already exists.";
        $uploadOk = 0;
    }

    // Check file size
    if ($_FILES["file"]["size"] > 500000) {
        $response = "Your file is too large.";
        $uploadOk = 0;
    }

    // Allow certain file formats
    $allowedFormats = ["jpg", "jpeg", "png", "gif"];
    if (!in_array($imageFileType, $allowedFormats)) {
        $response = "Only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }

    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo $response;
    } else {
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
            echo "The file " . htmlspecialchars(basename($_FILES["file"]["name"])) . " has been uploaded.";
        } else {
            echo "There was an error uploading your file.";
        }
    }
}

?>

				
			

In this example, we use jQuery to handle the form submission and send the file to the server via AJAX, providing a seamless user experience.

Conclusion :

Uploading images in PHP can be done in various ways, from basic form submissions to advanced AJAX techniques. Whether you need a simple solution or a more robust system with validation and error handling, the methods outlined in this article should cover your needs.

We hope this article has provided you with the knowledge to handle image uploads effectively in PHP. Happy coding!

Scroll to Top