Created
March 21, 2011 11:03
-
-
Save mattattui/879303 to your computer and use it in GitHub Desktop.
Safely handling a PHP file upload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (isset($_FILES['myfile'])) { | |
if ($_FILES['myfile']['error'] != UPLOAD_ERR_OK) { | |
// Handle your error here, the upload didn't work. | |
my_upload_error(); | |
} elseif (!is_uploaded_file($_FILES['myfile']['tmp_name'])) { | |
// File was not uploaded legitimately. Handle as you see fit. | |
my_upload_error(); | |
} else { | |
// So far, so good. Now to check the file itself. | |
$image_info = getimagesize($_FILES['myfile']['tmp_name']); | |
if (!$image_info) { | |
// The file isn't an image | |
my_upload_error(); | |
} elseif (!in_array($image_info[2], | |
array(IMG_GIF, IMG_JPG, IMG_PNG))) { | |
// The file isn't an accepted type. | |
my_upload_error(); | |
} elseif (($image_info[1] * | |
$image_info[2] * | |
$image_info['channels']) | |
> 2097152) { | |
/* This is a CRUDE calculation of the uncompressed size | |
* of the image (width x height x channels). We're rejecting | |
* if it's over 2Meg. Of course, that's a hard concept to | |
* explain to normal site users, so explain it to them in | |
* width and height terms. 2 Meg is about 1400 pixels square. | |
* Anyway, this image failed the size test, handle that here | |
*/ | |
my_upload_error(); | |
} else { | |
/* Everything looks good. Now you can use | |
* move_uploaded_file() to put the image somewhere, generate | |
* a thumbnail from it, or whatever you need to do. | |
*/ | |
do_stuff_here(); | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Read http://inanimatt.com/php-filtering.php for an explanation of this example.
NOTE:
do_stuff_here()
andmy_upload_error()
are example functions not included here.