Gcobani Mkontwana

Gcobani Mkontwana

  • 963
  • 821
  • 1.2k

How to upload an image and display it using php and html?

Nov 25 2024 2:55 PM

Hi Team

I need some help, want to upload an display an image using php and html the code is not displaying an image when uploaded. the back end works fine.

 

// html

         <img src="images/default.jpg" alt="user" id="profile-img">
                    </div>
                    <div class="pro-user-bio">
                        <ul>
                            <li>
                                <h4>Sam Anderson</h4>
                            </li>
                            <li>Student Id: ST17241</li>
                            </li>
                        </ul>
                    </div>
                    <form action="upload_file.php" method="POST" enctype="multipart/form-data">
                        <label for="profilePicture">Choose an image to upload:</label>
                        <input type="file" name="profilePicture" id="profilePicture" required onchange="previewImage(event)">
                        <button type="submit" class="upload-btn">Upload Image</button>
                    </form>
                    
                </div>

//php

<?php
session_start(); // Start the session to store the image filename

// Define the target directory for images
$targetDir = __DIR__ . "/images/";
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($_FILES["profilePicture"]["name"], PATHINFO_EXTENSION));

// Check if the file is an image
if (isset($_FILES["profilePicture"]["tmp_name"]) && $_FILES["profilePicture"]["tmp_name"] !== "") {
    $check = getimagesize($_FILES["profilePicture"]["tmp_name"]);
    if ($check !== false) {
        $uploadOk = 1;
    } else {
        echo "File is not an image.<br>";
        $uploadOk = 0;
    }
} else {
    die("No file was uploaded or invalid file input.");
}

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

// Allow certain file formats
if (!in_array($imageFileType, ["jpg", "jpeg", "png", "gif"])) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.<br>";
    $uploadOk = 0;
}

// Attempt to upload the file
if ($uploadOk == 1) {
    // Generate a unique filename for the uploaded image
    $targetFile = $targetDir . uniqid("profile_") . "." . $imageFileType;

    if (move_uploaded_file($_FILES["profilePicture"]["tmp_name"], $targetFile)) {
        // Store the filename in the session to remember the uploaded image
        $_SESSION['profile_image'] = $targetFile;
        echo "The file has been uploaded.<br>";
    } else {
        echo "Sorry, there was an error uploading your file.<br>";
    }
} else {
    echo "File upload failed.<br>";
}

// Redirect back to the dashboard
header("Location: dashboard-user.php");
exit;
?>