How to Upload Image in PHP


Image upload is simple code to understand and execute it. We need to take care of following points :-
– We Need to create Html form with the input type file and submit button
– Form should be enctype=”multipart/form-data”
– Image Validation to check the Image is of Perfect size/type
– We need to check that is image already exist or its the new image
– If the Image is uploaded successfully then we need to show the success message.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Include and Include Once Examples in PHP</title>
<!--We have created simple form so we can upload any file from this browse button-->
<form action="fileupload.php" method="post" name="fileuplaod" id="fileuplaod"enctype="multipart/form-data">
<td><label for="file">Filename:</label>
<input type="file" name="myfile" id="myfile">
<td><input type="submit" name="submit" value="Submit">
//Now we will check if file exist to upload then we will use the code of upload
if ($_FILES["myfile"]["error"] > 0)
//If no file exist then error message
echo "Error: " . $_FILES["myfile"]["error"] . "<br>";
echo "File Name: " . $_FILES["myfile"]["name"] . "<br>";
echo "File Type: " . $_FILES["myfile"]["type"] . "<br>";
echo "File Size: " . ($_FILES["myfile"]["size"] / 1024) . " kB<br>";

// Now we will check the validation of file type
$filetype = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["myfile"]["name"]);
$ft_name = end($temp); //This will give the file type
if ((($_FILES["myfile"]["type"] == "image/gif")
|| ($_FILES["myfile"]["type"] == "image/jpeg")
|| ($_FILES["myfile"]["type"] == "image/jpg")
|| ($_FILES["myfile"]["type"] == "image/pjpeg")
|| ($_FILES["myfile"]["type"] == "image/x-png")
|| ($_FILES["myfile"]["type"] == "image/png"))
&& ($_FILES["myfile"]["size"] < 200000000)
&& in_array($ft_name, $filetype))
//If file is proper then we will move forward or it will go in the else part
if (file_exists("upload/" . $_FILES["myfile"]["name"]))
//If file already exist then it will go in this if condition and display this error message
echo $_FILES["myfile"]["name"] . " already exists. ";
//If the file is new and not exist then it will upload to the temp folder
move_uploaded_file($_FILES["myfile"]["tmp_name"],"temp/" . $_FILES["myfile"]["name"]);
echo "Stored in: " . "temp/" . $_FILES["myfile"]["name"];
echo "Invalid file Type or Size";


Comments are closed.