-2

i have written a php script which checks the image file for its extension.. such as JPG, JPEG, PNG, GIF uploaded thru an HTML form .

Now comes my problem which is, any 1 may upload any kind of file by giving it an extension of JPG, JPEG, PNG, GIF.

Can any one help me so that, one should strictly be able to upload only an image file and not any other file which carries just extension of Image file.

I tried hard .. but failed...Here is my php script which i have written

        <?php
        $target_dir = "images/";
        $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
        $uploadOk = 1;
        $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
        // Check if image file is a actual image or fake image
        if(isset($_POST["submit"])) {
            $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
            if($check !== false) {
                echo "File is an image - " . $check["mime"] . ".";
                $uploadOk = 1;
            } else {
                echo "File is not an image.";
                $uploadOk = 0;
            }
        }
        // Check if file already exists
        if (file_exists($target_file)) {
            $target_file = $target_dir . date('YmdHis') . '.' . $imageFileType;

            if (file_exists($target_file)) {
                echo "<h2>File with same name already exists. Try renaming your file and Uploading again.</h2>";
                $uploadOk = 0;
            }
        }
        // Allow certain file formats
        if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
            echo "<h2>Only JPG, JPEG, PNG & GIF files are allowed.</h2>";
            $uploadOk = 0;
        }
        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            echo "<h2><mark>ERROR</mark> :Sorry, your file was not uploaded.</h2>";
            echo "<a href='submitdesign.html'><h3>Click Here to TRY AGAIN.</h3></a>";
            exit;
        // if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
                echo "<h3>The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.</h3>";
            } else {
                echo "<h2><mark>ERROR</mark> : Maximum File Size Allowed is upto 2MB. Please Optimize your Image Size</h2>";
                echo "<a href='submitdesign.html'><h3>Click Here to TRY AGAIN</h3></a>";
                exit;

            }
        }
        ?>

4 Answers4

1

I made it like this:

function checkImageType($fileToCheck) {
    $allowed_extensions = array('png', 'jpg', 'jpeg', 'gif');
    $checkfilename = pathinfo($fileToCheck['file']['name'], PATHINFO_FILENAME);
    $extension = strtolower(pathinfo($fileToCheck['file']['name'], PATHINFO_EXTENSION));

    if(in_array($extension, $allowed_extensions) && function_exists('exif_imagetype')) {

         $allowed_types = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
         $detected_type = exif_imagetype($fileToCheck['file']['tmp_name']);
         if(!in_array($detected_type, $allowed_types)) {
            echo 'No image!';
            die;

         }

         else  {
            return true;
        }

    }
}
Polaris
  • 712
  • 7
  • 21
0

You will take the MIMETYPE of the file, with that you can validate with high fidelity.

You can use finfo() too.

EXAMPLE:

<?php
$imageType = explode('/', mime_content_type($yourimage));
$acceptedFormats = ['jpg', 'jpeg', 'png', 'gif', 'x-png', 'pjpeg', 'svg'];
if ($imageType[0] == 'image'){
    if (in_array($imageType[1], $acceptedFormats)){
        //RUN YOUR CODE
    }
} else {
    exit('ERROR FILE INVALID');
}
Community
  • 1
  • 1
capcj
  • 1,535
  • 1
  • 16
  • 23
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. – Jay Blanchard May 12 '17 at 13:05
0

This is a slower way to do it, it can be used a second level of validation. Handy for Android uploads which like to rename jpgs as png, breaking both imagecreatefrompng() and imagecreatefromjpeg()

        $imageInfo = getimagesize($target_file);
        switch ($imageInfo['mime']) {
            case "image/jpg":
            case "image/jpeg":
            case "image/pjpeg": //for IE
                //Handle jpg
                break;
            case "image/gif":
                //handle gif
                break;
            case "image/png":
            case "image/x-png": //for IE
                //handle png
                break;
        }

newer versions of PHP can do this

                switch(exif_imagetype($target_file)){
                    case IMAGETYPE_JPEG:
                        //handle jpg
                        break;
                    case IMAGETYPE_PNG:
                        //handle png
                        break;
                    case IMAGETYPE_GIF:
                       //handle gif
                        break;
                }

I've never tried performance testing to see which is faster.

If you want it to be smarter, use both versions and wrap it with this

 if(function_exists('exif_imagetype')) {
//code
}else{
//code
}
Trevor
  • 2,792
  • 1
  • 30
  • 43
0

The getimagesize() can give you the info regarding the uploaded file as:

if(@is_array(getimagesize($mediapath))){
  $image = true;
} else {
  $image = false;
}

In normal cases getimagesize() gives an array like this:

Array (
  [0] => <INTEGER>//width
  [1] => <INTEGER>//height
  [2] => 2
  [3] => width="<INTEGER>" height="<INTEGER>"
  ...//with extra info)

Also we get the mime type in the end as well.

Took the reference from here.

Community
  • 1
  • 1
Ankur Verma
  • 5,793
  • 12
  • 57
  • 93