php file upload script | php file upload example

This is php file upload script or php file upload example for uploading file from your computer system to remote server. For uploading file in php,we are going to write simple php file upload script. First of all, we need a html form. So make form as given below:
<form name="upload_form" id="upload_form" method="post" action="uploader.php" 
enctype="multipart/form-data">
<table>
<tr><td>Select File</td><td><input type="file" name="myfile" id="myfile" /></td></tr>
<tr><td></td><td><input type="submit" name="btnUpload" id="btnUpload" value="Upload" />
</td></tr>
</table>
</form>

As you see, action attribute is set uploader.php file which will help in uploading file. In above form another attriubute enctype is used. This attribute specifies which content-type to use when submitting the form. Its value "multipart/form-data" is set when binary data is uploaded. Next Html input type is file, It makes a button on web page to select a file to upload. And last Html input type is submit button.

Next step is making uploader.php file for uploading.



<?php
$allowedExts=array("jpeg","jpg","png","gif");//allowed extensions
$uploadPath="/var/www/html/upload/"; //Target path
$name=$_FILES['myfile']['name']; //Name of uploaded file
$size=$_FILES['myfile']['size'];//Size of uploaded file
$error=$_FILES['myfile']['error']; //Error in uploading
$temp=$_FILES['myfile']['tmp_name']; //temporary name of uploaded file
$ext=pathinfo($name, PATHINFO_EXTENSION); //Getting extension of uploaded file
if(in_array($ext,$allowedExts)){

//Checking extension of uploaded file

if($size<100000){ //Checking size of uploaded file
if(move_uploaded_file($temp,$uploadPath.$name)) //moving file to desired location
{
echo "File is uploaded successfully.";
}
else
{
echo "Could not upload file.";
}
}
else
{
echo "File size more than 100KB is not allowed.";
}
}
else
{
echo "This type of file is not allowed.";
}
?>

In above coding, array of allowed extensions is made. In next line path of folders is set where file will be uploaded. Set write permission for upload folder.

In php global array $_FILES keeps information of uploaded file. Its first index is name of file input and second index is like name,size type and error etc. as given below.

$_FILES['myfile']['name']; For original name of file.
$_FILES['myfile']['size']; For file size in KB.
$_FILES['myfile']['error']]; For error if any.
$_FILES['myfile']['tmp_name']; For temporary name of file on server side.

We used pathinfo function to find extension of uploaded file. First of all we checked, is file allowed or not?, then size of file is checked.For security reasons we added all these restrictions. Finally we store the file at desired location with help of move_uploaded_file function. The function move_uploaded_file returns TRUE on success.