pTutorial

New way to learn PHP Example

PHP upload image script

Upload Image using PHP

You can upload image to the server using html and PHP, First of all make a simple form using html that have one browse button and one submit button.

In this form there are a lot of formatting tag. You can make your upload script very attractive using CSS.

PHP script to create the image upload script




<html>
<head>
<title>upload_file</title>
</head>
<body>
<center>
<form action="ad.php" method="post" enctype="multipart/form-data" 
name="upload">
<table width="300" border="10">
<tr>
<td>Select File</td>
<td><input name="file" type="file" /></td>
</tr>
<tr>
<td colspan="2"><center>
<input name="sub" type="submit" value="upload" />
</center></td>
</tr>
</table>

</form>
</center>
</body>
</html>
<?php
error_reporting(0);
if(isset($_POST['sub'])) 
{ 
$name=$_FILES['file']['name'];
$type=$_FILES['file']['type'];
$size=$_FILES['file']['size'];
$tmp=$_FILES['file']['tmp_name'];

if($name=='')
{
echo"<center> <font color='pink'><h2>choose image file first
</h2></font></center>";   

exit();
}

if(( $type == "image/jpeg" )||($type=="image/gif")||($type=="image/png"))
{
if($size<=500000)
{
if (file_exists( $_FILES["file"]["name"]))
{
echo"<center> <font color='pink'><h2>File already are there, select another one
<
/h2></font></center>";   

exit();
}

move_uploaded_file($tmp,"$name");		
echo"<center> <font color='pink' ><h2>upload completed
</h2
></font><br>".""."<img src=$name height='300'
width='300'> </center>";

echo "File Details"."<br/>";
echo "Name of file:".$name."<br/>";
echo "Size of file in byte:".$size."<br/>";
echo "Type of file:".$type."<br/>";
echo "Location of file:".$tmp."<br/>";
}

else
{
echo"<center> <font color='pink'><h2>File is very large<
/h2></font></center>";   					  }

}		   
else
{
echo"<center> <font color='pink'><h2> only jpeg, 
png, gif supported</h2></font></center>";   			
		  } 


}

?>


First of all take image attribute into the different variables like name, type and size etc.

In line number 34 check file is selected or not if file is selected then ok otherwise it will give a message and stop script.

In line number42 check supported type of image, in this case only jpeg, gif and png allowed.

In line number 46 check the file is exist or not, if file is not exist the ok otherwise it will give message and stop execution of script.

In line number 44 check allowed size, in this case allowed size is 500000 byte (488.28 kb) allowed.

In line number 56 move_uploaded_file() is used to store that file in given location. In this case same folder is the file's location, where PHP program is stored.

From line number 61 to line number 67 file details will be displayed like name of file, type and size of image.

Note:Size will be in Byte.

Output

Select File

QUOTES OF THE DAY

Goal is tired by fire, brave men by adversity.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER