If you want to display the selected image immediately through the file input, then you should preview an image before uploading using the PHP
In this tutorial, you will learn to upload a single image with a preview using PHP & jQuery. So that you can easily confirm whether the selected image is right or not before uploading it to the server.
By default When you browse an image from the local system, It will not display, only its name extension will be shown. So, you will have to write jQuery code to preview the image just after choosing an image and then upload it using PHP.
Once you learn it, You can easily preview other types of file formats by using our jQuery code that is created for the image preview feature.
Upload Image with Preview using PHP
Now, let’s start coding to upload the image with a preview using PHP
You should also learn the following –
Create File Upload Form
<form method="post" enctype="multipart/form-data"> <input type="file" name ="image" id="image"> <div id="preview"></div> <input type="submit" name="submit"> </form>
Explanation –
- This HTML form uses the POST method and enctype “multipart/form-data” for file uploads.
- It includes an input element of type “file” with the name “image” and an id “image” for selecting an image file.
- A div with the id “preview” is provided for displaying a preview of the selected image.
- The form includes a submit button with the name “submit.”
- When the form is submitted, the selected image file will be processed by the server-side script.
Preview Image using jQuery
This JavaScript code defines a function, imagePreview
, to display a preview of the selected image in an HTML element with the id “preview” when a file input with id “image” changes.
function imagePreview(fileInput) { if (fileInput.files && fileInput.files[0]) { var fileReader = new FileReader(); fileReader.onload = function (event) { $('#preview').html('<img src="'+event.target.result+'" width="300" height="auto"/>'); }; fileReader.readAsDataURL(fileInput.files[0]); } } $("#image").change(function () { imagePreview(this); });
Explanation –
- This JavaScript function, “imagePreview,” takes a file input element as a parameter.
- It checks if a file is selected, and if so, it creates a FileReader object.
- The FileReader’s onload event sets the HTML content of the element with the id “preview” to an image tag displaying the selected image with a maximum width of 300 pixels.
- The FileReader reads the selected file as a data URL.
- The $(“#image”).change() event listener triggers the imagePreview function when the content of the file input with the id “image” changes, enabling real-time image preview.
Upload an image using PHP
This PHP script handles image uploads on form submission, checking file type and moving the file to a specified directory while providing appropriate success or error messages.
<?php // uploading imahe on submit if(isset($_POST['submit'])){ upload_image(); } function upload_image(){ $uploadTo = "uploads/"; $allowedImageType = array('jpg','png','jpeg','gif','pdf','doc'); $imageName = $_FILES['file']['name']; $tempPath=$_FILES["file"]["tmp_name"]; $basename = basename($imageName); $originalPath = $uploadTo.$basename; $imageType = pathinfo($originalPath, PATHINFO_EXTENSION); if(!empty($imageName)){ if(in_array($imageType, $allowedImageType)){ // Upload file to server if(move_uploaded_file($tempPath,$originalPath)){ echo $fileName." was uploaded successfully"; // write here sql query to store image name in database }else{ echo 'image Not uploaded ! try again'; } }else{ echo $imageType." image type not allowed"; } }else{ echo "Please Select a image"; } } ?>
Explanation –
- The PHP script checks if the form is submitted and calls the function
upload_image()
if true. - The
upload_image()
function sets the upload directory, allowed image types, and retrieves the image details from the submitted form. - It constructs the target path for the uploaded image.
- The script checks if the image is not empty and if its type is allowed.
- If conditions are met, the script moves the uploaded file to the specified directory and echoes a success message; otherwise, it provides appropriate error messages.
- A placeholder comment indicates where you might insert an SQL query to store the image name in a database.