Check picture file type and size before file upload in php

php

Solution

Note that you might not want to rely on file extensions to determine file type. It would be rather easy for someone to upload an executable file with a `.png` extension for example. A mime-type can also easily be forged by a malicious client to pass as an image. Relying on that information is a security risk.

PHP Documentation: The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.

Try loading the images with `gd` (`getimagesize()`) to make sure they are actually valid images (and not just random files pretended with the header of an image file... `finfo_file` relies on those headers).

if($_FILES["imagefile"]["size"] >= 2120000) {
  echo "F2";
  die();
} else {
    $imageData = @getimagesize($_FILES["imagefile"]["tmp_name"]);

    if($imageData === FALSE || !($imageData[2] == IMAGETYPE_GIF || $imageData[2] == IMAGETYPE_JPEG || $imageData[2] == IMAGETYPE_PNG)) {
      echo "F2";
      die();
    }
}

If you really must use the extension to verify if the file is an image, use `strtolower()` to put the extension into lowercase.

$filecheck = basename($_FILES['imagefile']['name']);
$ext = strtolower(substr($filecheck, strrpos($filecheck, '.') + 1));

if (!(($ext == "jpg" || $ext == "gif" || $ext == "png") && ($_FILES["imagefile"]["type"] == "image/jpeg" || $_FILES["imagefile"]["type"] == "image/gif" || $_FILES["imagefile"]["type"] == "image/png") && 
    ($_FILES["imagefile"]["size"] < 2120000))){
    echo "F2";
    die();
}

Problem

I have the following code: ``` $filecheck = basename($_FILES['imagefile']['name']); $ext = substr($filecheck, strrpos($filecheck, '.') + 1); if (($ext == "jpg" || $ext == "gif" || $ext == "png") && ($_FILES["imagefile"]["type"] == "image/jpeg" || $_FILES["imagefile"]["type"] == "image/gif" || $_FILES["imagefile"]["type"] == "image/png") && ($_FILES["imagefile"]["size"] < 2120000)){ } else { echo "F2"; die(); } ``` What i need to do is check if the uploaded file is a jpg/gif/png and that its less than 2 megs in size. If its larger than 2 megs, or not the right file type, i need to return/echo F2 (error code for api). When i use the code above to process a 70k jpg file, it returns F2. SUBNOTE the picture im uploading has an extension of .JPG. Could case be a factor? If so, how do i accommodate for that?

Original source