Posted by Arjun on Thursday 26th January 2012

File Uploading with PHP ?

This script will allow you to upload files from your browser to your hosting, using PHP.

Uploading Files to a server can be broken down into two parts :

      As usual we need an HTML form with browse option to visitors to choose images
      A script to process the upload, validate the file, name it and place it in the file system or show status Message

For uploading form, the enctype attribute should be set to multipart/form-data and set input type parameter set to “file”.

An HTML Upload form allows people to choose the file they want to upload.

<form action="upload.php" method="post"
<label for="file">File name:</label>
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />

Then create upload.php file this page will execute if user submit form.upload.php file contain php code to validate given data,and to upload to the destination folder

if(!isset($_POST)){die('You can not access this file directly');}
//avoid direct accessing to this file.
 if(isset($_POST['submit'])) { 
 // start uploading if user submit 
  if(!empty($_FILES['file']['name'])) { 
  // check for user selection  
   if ((($_FILES["file"]["type"] == "image/gif")|| ($_FILES["file"]["type"] == "image/jpeg")|| ($_FILES["file"]["type"] == "image/pjpeg"))) { 
   // check for file extension here i am allowing gif,jpeg,pjpeg formats only 
	 if(($_FILES["file"]["size"] < 30000)) { 
     // check for file size and it should be greater than 3MB
       if ($_FILES["file"]["error"] > 0) { 
       //check for errors 
            echo "Error: " . $_FILES["file"]["error"] . "<br />"; 
            // if any errors encountered we are printing here 
		else { 
        // if uploading process success , execute this area 
	     echo "Upload: " . $_FILES["file"]["name"] . "<br />"; 
         // print file name
		 echo "Type: " . $_FILES["file"]["type"] . "<br />"; 
         // print type
		 echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; 
         //print size
	     move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $_FILES["file"]["name"]); 
         // Here we are moving uploaded file to upload folder with move_uploaded file function 
		 } else { echo 'file too large'; } 
         // if file size is more then above declaration 
	  } else { echo 'invalid file'; }
       // if file is not in our mentioned format , print this error message 
   else {
         echo 'plz select file'; //input filed empty return this error message