How can PHP be used to create an upload script with a preview feature?

To create an upload script with a preview feature in PHP, you can use a combination of HTML, CSS, and PHP. The HTML form will allow users to select an image file to upload, and the PHP script will handle the file upload process. Additionally, you can use PHP to display a preview of the uploaded image before finalizing the upload.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && 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") {
        move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
        echo "Image uploaded successfully:<br>";
        echo "<img src='" . $target_file . "' width='200'>";
    } else {
        echo "Invalid file format. Please upload a JPG, JPEG, PNG, or GIF file.";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Image Upload with Preview</title>
</head>
<body>
    <form method="post" enctype="multipart/form-data">
        <input type="file" name="image" accept="image/*">
        <input type="submit" value="Upload">
    </form>
</body>
</html>