Skip to content

Uploading Images With PHP ?

Last updated on January 17, 2018

This Tutorial takes you through How to make a PHP Image Uploading Script, rather than uploading images to a database this tutorial shows you how to upload images to your web server.

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

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

Here is my Html Script:

Here is my PHP Script, upload.php
this PHP Script will execute if the user submits form, and validate given data than upload it to the destination folder, I am writing inline comments in the code, just go through it and let me know if you have confusion or further improvement in coding or tutorial.

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 file size should be less 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 } }

Used PHP functions in the Tutorial:
die() : This language construct is equivalent to exit(), it will prints the error message and exit the current script.
isset() : Determine if a variable is set and is not NULL.
move_uploaded_file() : The move_uploaded_file() function moves an uploaded file to a new location. This function returns TRUE on success, or FALSE on failure.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments