Skip to content

File Uploading with PHP ?

Last updated on January 17, 2018

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.

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"] . "
"; // if any errors encountered we are printing here } else { // if uploading process success , execute this area echo "Upload: " . $_FILES["file"]["name"] . "
"; // print file name echo "Type: " . $_FILES["file"]["type"] . "
"; // print type echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb
"; //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 } }
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments