Here we are going to see How to do PHP File upload by creating an HTML form, and PHP upload script to upload image files to our server.
On social media sites like Facebook, you have seen the field and button to upload files, especially images.
Using those fields you can upload your images to social media sites and share them with others.
These features are just like any other features on the web created using a programing language.
and in our case, we are going to use PHP for it.
Since PHP is primarily created for Websites you can easily create a PHP file upload form.
And here in this post, I am going to instruct you on how to do so
Configure the php.ini file
The first step toward creating your own PHP file upload script is to check whether file upload is allowed on your server.
Inside the root folder of your website, you will find a file named php.ini
to look for this.
If it does not exist create this file and make sure to add this line of code to it:
file_uploads = On
When the file upload is not on, you would not be able to upload files on that server or website.
Create the HTML Upload form
Once we allowed file uploads the next step is to create a user interface from where users can upload files to the server.
To do this, we have to create an HTML form with a file field and submit button.
We also have to point out our upload script which in this case is upload.php
.
Here is how we can create it:
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<!-- Creating field to upload file -->
<input type="file" name="fileToUpload" id="fileToUpload">
<!-- Creating submit button -->
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Here is a further explanation on this code:
- We use ‘upload.php’ as action becouse we want to run that script to upload file on our server.
- You may also notice that we write enctype
multipart/form-data
. we write it when your form includes any<input type="file">
elements - Everytime when we upload something on server its better to use ‘post’ instead of ‘get’ since it is much more secure.
- We use inpute type : file. This field is use for media upload.
- Submit button is require since once we upload image we need to confirm by hitting sumit button.
Create PHP File Upload Script
Once we created a visual interface to upload files using HTML the next obvious step is to create a PHP file upload script that would handle the file upload process.
Now follow this process:
- First Create a PHP file named “upload.php”.
- Now write php markup and add following variable there:
# Location to upload file $target_dir = "uploads/"; # Change Name of file $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); # Check if uploaded file is ok $uploadOk = 1; # Check file type of uploaded file $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
- Once that done, add following statment to check uploaded image is actual image of fack:
if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } }
Necessary file checks
When we’re going to upload images or any kind of files on the server, we have to take some prosecution mesures.
For example, we have to check the right file type is being uploaded, whether the file already exists on the server, the file is too made, and so on.
Check If file is already exist?
If a particular file that we are trying to upload on the server, already exists; we have no need to upload it again.
Here is the code that we can use to check if the file is already exist on the server:
// Code Check if file already exists on server
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
Limit file size
Most of the time we don’t want to upload very large files on our server.
Big files not only take too many server resources, but they also take too much time to upload and process.
In our case, we named our HTML file input field “file to upload”.
Using this as an array we can extract the size of the file and if it is too large we stop this from uploading.
Here is how to limit file size:
# How to check file size
if ($_FILES["fileToUpload"]["size"] > 1000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
Here we can replace “1000000” with any size that we can think is too big for an image.
Limit File Type
Most of the time, when we provide an upload field to the user, we have a very specific file type in our mind.
It can be the image, audio, video, document, and so on.
Depending on what kind of file type we want users to upload we can Limit file type in our “upload.php”.
For example, in our case we only want users to upload images, So we can restrict to only image extensions:
# Allow only certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
Finish your PHP file upload script
So following all the logic, restriction our final PHP upload script would look like this:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["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 file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
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.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>