In this php tutorial example we do upload image using file upload and display image on same page in img control after uploading image.
PHP upload is a single-line, built-in function invocation. Any user inputs, especially files, can not be processed without proper filtering. Why? Because people may upload harmful files to the server.
After file upload, the status has to be shown in the UI as an acknowledgment. Otherwise, showing the uploaded image’s preview is the best way of acknowledging the end user.
Steps to upload and display the image preview on the browser
- Show an image upload option in an HTML form.
- Read file data from the form and set the upload target.
- Validate the file type size before uploading to the server.
- Call the PHP upload function to save the file to the target.
- Display the uploaded image on the browser
1. Show an image upload option in an HTML form
This code is to show an HTML form with a file input to the user. This form is with enctype=”multipart/form-data” attribute. This attribute is for uploading the file binary to be accessible on the PHP side.
<form action="" method="post" enctype="multipart/form-data">
<div class="row">
<input type="file" name="image" required>
<input type="submit" name="submit" value="Upload">
</div>
</form>
Read file data from the form and set the upload target
<?php
if (isset($_POST["submit"])) {
// Check image using getimagesize function and get size
// if a valid number is got then uploaded file is an image
if (isset($_FILES["image"])) {
// directory name to store the uploaded image files
// this should have sufficient read/write/execute permissions
// if not already exists, please create it in the root of the
// project folder
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
// Validation here
}
}
?>
Validate the file type size before uploading to the server
<?php
// Check image using getimagesize function and get size
// if a valid number is got then uploaded file is an image
if (isset($_FILES["image"])) {
// directory name to store the uploaded image files
// this should have sufficient read/write/execute permissions
// if not already exists, please create it in the root of the
// project folder
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"]);
if ($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if the file already exists in the same path
if (file_exists($targetFile)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size and throw error if it is greater than
// the predefined value, here it is 500000
if ($_FILES["image"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Check for uploaded file formats and allow only
// jpg, png, jpeg and gif
// If you want to allow more formats, declare it here
if (
$imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif"
) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
?>
Full PHP code for image upload and display
<?php
if (isset($_POST["submit"])) {
// Check image using getimagesize function and get size
// if a valid number is got then uploaded file is an image
if (isset($_FILES["image"])) {
// directory name to store the uploaded image files
// this should have sufficient read/write/execute permissions
// if not already exists, please create it in the root of the
// project folder
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"]);
if ($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if the file already exists in the same path
if (file_exists($targetFile)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size and throw error if it is greater than
// the predefined value, here it is 500000
if ($_FILES["image"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Check for uploaded file formats and allow only
// jpg, png, jpeg and gif
// If you want to allow more formats, declare it here
if (
$imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif"
) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) {
echo "The file " . htmlspecialchars(basename($_FILES["image"]["name"])) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload and display image in PHP</title>
</head>
<body>
<div class="container">
<h1>Upload an Image</h1>
<form action="" method="post" enctype="multipart/form-data">
<div class="row">
<input type="file" name="image" required>
<input type="submit" name="submit" value="Upload">
</div>
</form>
<h1>Display uploaded Image:</h1>
<?php if (isset($_FILES["image"]) && $uploadOk == 1) : ?>
<img src="<?php echo $targetFile; ?>" alt="Uploaded Image">
<?php endif; ?>
</div>
</body>
</html>
Create a directory called “uploads” in the root directory of the downloaded example project. Uploaded images will be stored in this folder.
Note: The “uploads” directory should have sufficient file permissions.
Good luck and I hope this article can be useful. See you in the next article…
If you enjoyed this tutorial and learned something from it, please consider sharing it with our friends and followers! Also like to my facebook page to get more awesome tutorial each week!