How to upload Image in PHP

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.

Unknown extension!';
 			$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 '

You have exceeded the size limit!

'; $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 '

Copy unsuccessfull!

'; $errors=1; }}}} //If no errors registred, print the success message if(isset($_POST['Submit']) && !$errors) { echo "

File Uploaded Successfully! Try again!

"; } ?>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Privacy Policy · Contact · Sitemap

© 7Tech – Programming and Tech Tutorials