It’s 2018 and uploading files is not a must have but a required feature for many websites. So for you as a web developer, it’s really important for you to know how to upload a file on a server with PHP. It’s easy to upload files using php.

Before learning how to use PHP to upload files you first need to check that if the max upload size is greater than or equal to the size of files your users are going to upload. If not you can see how to increase max upload size with the php.ini file or increase max upload size with the .htaccess file. Once you are done don’t forget to restart apache/nginx.

Now let’s get started.

Create The HTML Form

First, we need to create the HTML form that will allow users to upload files.

<form action='upload.php' method='post' enctype='multipart/form-data'>
Select Files To Upload :
<input type="file" name='filestoupload' value="Upload Files" />
<button type="submit"> Upload </button>
</form>

The file upload form is just like a normal form But it you need to make sure these things  –

  • The form method should be set to post, like this  – method=upload.
  • The enctype attribute should be set to multipart/form-data to allow file uploads, like this – enctype=’multipart/form-data’.

And the input element since the user is going to upload a file we will be using the input type as file. It will show a browse button so that the user can click and select the files to upload.

This is all that you need to do in HTML side. Now your users will be able to upload files but we need to handle the uploaded files using php.

Creating The File Upload Script (upload.php)

In the file upload from we had set the action to upload.php. So we have to create the upload.php file which is the upload script to handle the uploaded files.

Basically, our file is already uploaded to the server but as a temporary file therefore what our script will do is that it will move the uploaded file from the temporary file location to our desired location.

$upload_dir = "uploads/";
$target_file = $upload_dir . basename($_FILES["filestoupload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file ". basename( $_FILES["filestoupload"]["name"]). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}

The above code is a very basic code which can be used for file uploading. So you can paste the above code into the upload.php file to test file uploading but I would not recommend you to use the above code in a real project. For using the code into real projects it needs to be improved by adding a few checks to it. In case if you want your users to upload anything of any size then you may go with this code.

Now let’s improve our file upload script so that it can be used in a real project.

First, we will create a variable called uploadOK and set it to true and also a variable for storing the file type.

$upload_dir = "uploads/";
$target_file = $upload_dir . basename($_FILES["filestoupload"]["name"]);
$uploadOK = true ;
$FileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

Limit File Size of Uploaded File

Since we all do have a limitation of disk space on our web servers we just can’t allow our users to allow files on any size, therefore we need to add a limitation to it. like this –

// Check file size
if ($_FILES["fileToUpload"]["size"] < 5000000) {
echo "Sorry, your file is too large.";
$uploadOK = false ;
}

The above piece of code will add a limitation of 500000 Bytes which is 5 MB. So just replace 500000 with the number of bytes you want to limit. If you aren’t good at converting you can use our very own converter for it use the MB to bytes converter or the Bytes Converter.

Check If File Exists

If you continue to upload a file without checking if the file exists then it will replace the current file with the new one. So it’s really important to check if the file already exists. here is how you can do it –

// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOK = false ;
}

Tip: In case if you don’t want the upload to fail due to this you can use rename function to rename existing files with a new name.

Limit File Type

We just can’t allow users to upload any file they want to because you have to pay for the storage for those files on your server and yes it isn’t safe as well. Let’s say you want your users to upload only images you can do something like this –

// Allow Only Image file formats
if($FileType != "jpg" && $FileType != "png" && $FileType != "jpeg"
&& $FileType != "gif" ) {
 echo "Sorry, only JPG, JPEG, PNG &amp; GIF Image files are allowed.";
 $uploadOk = false ;
}

or if you want your users to upload only videos do it like this –

 
// Allow Only Video file formats
if($FileType != "mp4" && $FileType != "3gp" &&; $FileType != "avi"
&& $FileType != "flv" && $FileType != "mov" ) {
 echo "Sorry, only mp4, 3gp, avi, flv, &amp; mov video files are allowed.";
 $uploadOk = false ;
} 

The Final Complete Upload Script

Till now showed you all pieces of code you need to know.Now we just need to get all the code pieces together so that we can create the most awesome php upload script !!

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOK = true ;
$FileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOK = false ;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] < 5000000) {
 echo "Sorry, your file is too large.";
 $uploadOK = false ;
}

// Allow only image&nbsp; file formats
if($FileType != "jpg" && $FileType != "png" && $FileType != "jpeg"
&& $FileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG &amp; GIF files are allowed.";
$uploadOK = false;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOK == false) {
echo "Sorry, your file was not uploaded due to the issues listed";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was some issue while uploading your file.";
}
}
?>

Finally, this a complete script which can be used. and I hope you understood all that we have done in the script and just In case if you didn’t get anything don’t hesitate to ask me within the comments section below I would be glad to answer you.

And yes if my post did help you don’t forget to share on social media it will help us and others to grow.