PHP Upload only image using file upload



PHP upload only images

In this php file upload tutorial we will learn to make restriction to upload image as per our requirement.
Here, we allow only images to be uploaded using file upload in php, so we need to check extension of uploaded file, to ensure that is image or not.

Here, we take a php file upload example that allow to upload only ‘jpg’, ‘jpeg’, ‘gif’ and ‘png’ image.

For check upload file extension.

pathinfo(“image_name”, PATHINFO_EXTENSION)


PHP File upload example

Example of check extension of uploading image.

<html>
<head>
<title>PHP File type check example</title>
</head>
<body>

<form action="fileupload.php" enctype="multipart/form-data" method="post">
Select image :
<input type="file" name="file"><br/>
<input type="submit" value="Upload" name="Submit1">

</form>

<?php

if(isset($_POST['Submit1']))
{ 

$extension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);

if($extension=='jpg' || $extension=='jpeg' || $extension=='png' || $extension=='gif')
{
echo "File is image <br/>";
echo "File type = " . $extension;

}
else
{
echo "File is not image";
}
}


?>
</body>
</html>

The output of php example is :

php file upload
PHP upload image type check example

 

We can also do same above things using $_FILES[“file”][“type”] in php.

<?php

if($_FILES["file"]["type"]=="image/jpeg" || $_FILES["file"]["type"]=="image/gif")
{
//write upload code
}
else
{
echo "Error !!, Only jpeg and gif image allowed";
}

?>

 

3 thoughts on “PHP Upload only image using file upload

Leave a Reply to NITTU THANKACHAN Cancel reply

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