Image upload validation using php

hello guys,

sometime it is necessary to check whether the uploaded file is valid Image file or not ?  or sometime you need to allow user to upload only few image extension file.  let’s say you want to allow user to upload only (gif, jpeg, jpg, png) extension file.

so let’s go for coding.

HTML Coding

<body>
<form method="post" action="uploadimage.php" enctype="multipart/form-data">
<table>
<tr>
<td> Upload Image here : </td>
<td> <input type="file" name="file"> </td>
</tr>
<tr>
<td> <input type="submit" value="upload"> </td>
</tr>
</table>
</form>
</body>

PHP Coding (uploadimage.php)

<?php
$allowedExts = array("jpg", "jpeg", "gif", "png");
$arr = explode(".", $_FILES["file"]["name"]);
$extension = end($arr);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/jpg"))
&& in_array($extension, $allowedExts))
{
   if ($_FILES["file"]["error"] > 0)
    {
        echo "Error: " . $_FILES["file"]["error"] . "<br />";
    }
    else
    {
      move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $_FILES["file"]["name"] );
      echo "<script>alert('file uploaded successfully')</script>";
     }
 }
else
{
      echo "Invalid file";
}
?>

Please make sure that you have upload folder in your current directory.!

Hope you enjoy this small script!
🙂

Advertisements

5 thoughts on “Image upload validation using php

  1. Pingback: Avoiding the PHP GIF Security Issue | Web Developer Blog

  2. Its like you read my mind! You seem to know a lot about this, like you wrote the book in it or something. I think that you can do with a few pics to drive the message home a bit, but instead of that, this is fantastic blog. A fantastic read. I will definitely be back. ddgeeekbkgke

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s