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>
Related Questions
- Are there any best practices or alternative methods recommended for securing sensitive areas of a website in PHP?
- What are some common pitfalls to avoid when sorting data in ascending or descending order in PHP?
- How can a cleaner database design, such as using logical table and field names with prefixes, help prevent SQL errors in PHP?