This tutorial shows you how to upload an image on your server using PHP and html forms. You will also learn how to verify if the uploaded file is an image (by checking the extension of the file), if it doesn’t overtakes a size limit and how to change the uploaded file name.

Important: You must set the enctype form atribute to “multipart/form-data”, otherwise the form will not show you any errors, but it will also not upload your image or any file!

Here are the steps:

Step 1: Create a folder named images located in the path you are planning to place the php script you are about to create. Make sure it has write rights for everybody or the scripts won’t work ( it won’t be able to upload the files into the directory).

Step 2: Paste the following code into a php file.

Please read carefuly the comments. All steps are explained there.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
//define a maxim size for the uploaded images in Kb
 define ("MAX_SIZE","100"); 
 
//This function reads the extension of the file. It is used to determine if the file  is an image by checking the extension.
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }
 
//This variable is used as a flag. The value is initialized with 0 (meaning no error  found)
//and it will be changed to 1 if an errro occures.
//If the error occures the file will not be uploaded.
 $errors=0;
//checks if the form has been submitted
 if(isset($_POST['Submit']))
 {
 	//reads the name of the file the user submitted for uploading
 	$image=$_FILES['image']['name'];
 	//if it is not empty
 	if ($image)
 	{
 	//get the original name of the file from the clients machine
 		$filename = stripslashes($_FILES['image']['name']);
 	//get the extension of the file in a lower case format
  		$extension = getExtension($filename);
 		$extension = strtolower($extension);
 	//if it is not a known extension, we will suppose it is an error and will not  upload the file,
	//otherwise we will do more tests
 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
 		{
		//print error message
 			echo '<h1>Unknown extension!</h1>';
 			$errors=1;
 		}
 		else
 		{
//get the size of the image in bytes
 //$_FILES['image']['tmp_name'] is the temporary filename of the file
 //in which the uploaded file was stored on the server
 $size=filesize($_FILES['image']['tmp_name']);
 
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
	echo '<h1>You have exceeded the size limit!</h1>';
	$errors=1;
}
 
//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="images/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
	echo '<h1>Copy unsuccessfull!</h1>';
	$errors=1;
}}}}
 
//If no errors registred, print the success message
 if(isset($_POST['Submit']) && !$errors)
 {
 	echo "<h1>File Uploaded Successfully! Try again!</h1>";
 }
 
 ?>
 
 <!--next comes the form, you must set the enctype to "multipart/frm-data" and use an input type "file" -->
 <form name="newad" method="post" enctype="multipart/form-data"  action="">
 <table>
 	<tr><td><input type="file" name="image"></td></tr>
 	<tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
 </table>
 </form>

5 Responses so far.

  1. Liberty says:

    Gosh, I wish I would have had that informaiton earlier!

  2. Abhishek says:

    Thanks a lot. You have the perfect code I was searching for.

    Just one thing -
    For line 55, $newname=”images/”.$image_name; the images folder should preexist.

  3. Ankur Sharma says:

    Hi Abhishek,

    Thank you for your valuable comment.
    If you want to check the directory if it exist or not, if not then make that directory.
    Use this code before the line 57.

    if(!file_exists(“images”))
    {
    mkdir(“images”);
    }

  4. Good day! I just want to give a huge thumbs up for the great data you’ve got here on this post. I shall be coming again to your weblog for more soon.

  5. Nancy says:

    Thanks for the share!
    Nancy.R