Upload Image in PHP


You can upload image using PHP script to the specific location on the server.
In order to upload files on the server first you need to use file input element in your application. It allows you the functionality of selecting specific image files from your computer.
Create a file named UploadImage1.php as shown below:

<html>
<body>
<form action="UploadImage2.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /> <br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

When you select any file using this input element the information of the file is stored in the two dimensional array in following form:

Array
( [file] => Array
(
[name] => login_icon.gif
[type] => image/gif
[tmp_name] => C:\wamp\tmp\php6B.tmp
[error] => 0
[size] => 1531
)
)

     

Now create a file named UplaodImage2.php as shown below. It will first retrieve the information of the selected file from FILES array and determines weather the file is valid image file or not. If it is valid file then it will use copy() function to upload selected file to specific location.

<?php
echo "FileName:".$_FILES["file"]["name"]."<br/>";
echo "FileType:".$_FILES["file"]['type']."<br/>";
echo "FileSize:".$_FILES["file"]['size']."<br/>";
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000000))
{
copy($_FILES["file"]["tmp_name"],"C:/upload/".$_FILES["file"]["name"]);
echo "Stored in: " . "C:/upload/" . $_FILES["file"]["name"];
}
else
{
echo "Can Not Upload Image";
}
?>

Now run the file UploadImage1.php file

Upload Image

When you click on the submit button it will first check for the image type and if it is valid image file then it will upload image to specific location as shown below:

Upload Image

Download Projects


Download Programs