Image Upload in PHP

Image Upload in PHP

Here's a step-by-step guide to upload and display an image in PHP using AJAX

Step 1: HTML Form (index.html)

Create an HTML form with an input field of type "file" to allow users to upload images. Also, create a container div where the uploaded image will be displayed.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload and Display Image</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("#uploadForm").submit(function(e){
                e.preventDefault();
                var formData = new FormData(this);
                $.ajax({
                    url: 'upload.php',
                    type: 'POST',
                    data: formData,
                    success: function(response){
                        $("#imageContainer").html(response);
                    },
                    cache: false,
                    contentType: false,
                    processData: false
                });
            });
        });
    </script>
</head>
<body>
    <h2>Upload Image</h2>
    <form id="uploadForm" enctype="multipart/form-data">
        <input type="file" name="image">
        <button type="submit">Upload</button>
    </form>
    <h2>Uploaded Image</h2>
    <div id="imageContainer"></div>
</body>
</html>

Step 2: PHP Script to Handle Image Upload (upload.php)

Create a PHP script to handle the upload process. This script will move the uploaded image file to a designated folder on the server and return the path to the uploaded image.

<?php
if(isset($_FILES["image"])) {
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["image"]["name"]);
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
        echo "Only JPG, JPEG, PNG & GIF files are allowed.";
        exit();
    }
    if(move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
        echo '<img src="'.$target_file.'" width="300" />';
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

Ensure that you have a folder named "uploads" in the same directory as your PHP files to store the uploaded images.




Mahendra Pratap Singh

Hey there! I'm a Senior Full Stack Developer with 10 +years of experience in the tech world. I've spent a lot of time working with different tools and languages, like PHP, WordPress, Laravel, and CodeIgniter... Read More >>

Leave a Comment