Upload File Using PHP and Save in Directory | All PHP Tricks

Demo Download

Uploading file is one of the most common feature which we normally use in our daily life, we do upload pictures on Facebook, Twitter and other websites. So today I will share a tutorial about how to upload file using PHP and save/store that file in your web server directory.

Mục lục bài viết

HTML Form

<form name="form" method="post" action="upload.php" enctype="multipart/form-data" >
<input type="file" name="my_file" /><br /><br />
<input type="submit" name="submit" value="Upload"/>
</form>

We will need a form with one input field with file type. The action tag of form should point to the URL of PHP script file which actually perform the uploading task. It is also important to add enctype=”multipart/form-data” property in your form to upload file otherwise your file will not be uploaded.

PHP Script

if (($_FILES['my_file']['name']!="")){
// Where the file is going to be stored
	$target_dir = "upload/";
	$file = $_FILES['my_file']['name'];
	$path = pathinfo($file);
	$filename = $path['filename'];
	$ext = $path['extension'];
	$temp_name = $_FILES['my_file']['tmp_name'];
	$path_filename_ext = $target_dir.$filename.".".$ext;
 
// Check if file already exists
if (file_exists($path_filename_ext)) {
 echo "Sorry, file already exists.";
 }else{
 move_uploaded_file($temp_name,$path_filename_ext);
 echo "Congratulations! File Uploaded Successfully.";
 }
}

As you can see above I tried to use the variable name as its function so that you can easily understand what I am doing, I just check that if file already exist it will print the error otherwise file will be uploaded.

This tutorial is only for the basic learning purpose, if you want to implement it on your website so it is better to use more validation before uploading file.

//you can easily get the following information about file:
$_FILES['file_name']['name']
$_FILES['file_name']['tmp_name']
$_FILES['file_name']['size']
$_FILES['file_name']['type']

Validation such as file type (extension) or file size can also be check on the client side I also wrote tutorial Check File Size & Extension Before Uploading Using jQuery.

If you found this tutorial helpful so share it with your friends, developer groups and leave your comment.

Facebook Official Page: All PHP Tricks

Twitter Official Page: All PHP Tricks