As of PHP 4.1.0, the $_FILES array contains data about the uploaded files. This includes the MIME-type of the uploaded file. All you need to do is check that this begins with "image/" (JPEGs are image/jpeg, GIFs are image/gif, PNGs are image/png and so on). However, PHP doesn't check this: it relies on the browser's definition, which can be altered by the user.
PHP Code:
<?php
$file = $_FILES['nameOfInputElement'];
$isImage = explode("/", $file['type']);
$isImage = $isImage[0];
$isImage = ($isImage == "image");
if($isImage) {
// Do the file upload stuff, accept the file
} else {
// Yell at the user and die.
}
?>
If you're using a *n?x server with the file(1) utility installed, you can perform a simpler and far more reliable check using it:
PHP Code:
<?php
$file = $_FILES['nameOfInputElement'];
$mimetype = shell_exec("file -i " . $file['tmp_name']);
$mimetype = explode(": ", $mimetype);
$mimetype = $mimetype[1];
$isImage = explode("/", $mimetype);
$isImage = $isImage[0];
$isImage = ($isImage == "image");
if($isImage) {
// Do the file upload stuff, accept the file
} else {
// Yell at the user and die.
}
?>
There are also mimetype handling thingummies for PHP. See this for these - there are numerous deprecations and setup steps.
Bookmarks