Thomas
Thomas

Reputation: 5099

PHP Upload file filtering

Im trying to write an upload script that only accepts PNG images on upload. The upload script works fine but when I add the png image detection, it breaks.

Here is how I have it set up:

if ($_FILES) {

        if ($_FILES["file"]["type"] == "image/png") {

        $target_path = "uploads/";
        $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

        if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
            echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
            " has been uploaded";
        } else{
            echo "There was an error uploading the file, please try again!";
        }

        } else { echo "Not A PNG…";

        }

    }

When I upload a PNG image, I get the 'not a png' error - any ideas?

Upvotes: 0

Views: 3777

Answers (3)

deceze
deceze

Reputation: 522412

  1. Never use $_FILES[...]['type'] for anything. It's just an arbitrary, user supplied string which may or may not have anything to do with the actual file.
  2. Therefore, check the MIME type yourself.
  3. Enable error_reporting(E_ALL); ini_set('display_errors', true);, which would help you find your particular typo.
  4. Get used to failing early.

Example for 2 and 4:

if (!empty($_FILES['uploadedfile'])) {
    if ($_FILES['uploadedfile']['error'] !== UPLOAD_ERR_OK) {
        die('Error during upload');
    }
    if (exif_imagetype($_FILES['uploadedfile']['tmp_name']) !== IMAGETYPE_PNG) {
        die('Wrong file type');
    }
    ...
}

Upvotes: 2

Prof
Prof

Reputation: 2908

I have seen some servers not add the mime type image/png in the $_FILES variable... there is a slightly CPU heavier way:

if (@imagecreatefrompng($_FILES["file"]["tmp_name"])

The performance here will be slightly reduced as you are using the GD library to open the image canvas

If performance or lack of GD library is an issue, simply check the extension:

if (strtolower(end(explode('.',$_FILES["file"]["name"])) == 'png')

Note If you want to use the imagecreatefrompng function, it would be advisable to make sure GD is installed: if (function_exists('imagecreatefrompng'))


Important If you are cautious about memory usage (which you should be) do this

if ($image = @imagecreatefrompng($_FILES["file"]["tmp_name"]) {
  // Do something
  imagedestroy($image);
  }

Upvotes: 2

Ben D
Ben D

Reputation: 14489

It looks like you're referencing the file wrong in the IF statement:

if ($_FILES["file"]["type"] == "image/png") {

should be

if ($_FILES["uploadedfile"]["type"] == "image/png") {

("file" needs to be "uploadedfile")

Upvotes: 3

Related Questions