Unable to detect mime type. if I remove ($mime==\"image/jpeg\" || $mime==\"image/pjpeg\")
, it could upload the image successfully.
$mime = $_FILES[\
The name
and type
information for uploaded files should be seen as purely informational and never be used for anything serious, since it's user supplied information and can easily be spoofed. You should only ever look at the tmp_name
, error
and size
fields to determine if you want to accept a file. To find the actual MIME type of a file, use PHP's built-in functions:
if ($file['error'] == UPLOAD_ERR_NO_FILE) {
die('No file uploaded');
}
if ($file['error'] != UPLOAD_ERR_OK) {
die('Error during upload');
}
if (!$file['size'] || !is_uploaded_file($file['tmp_name'])) {
die('File is weird');
}
$extensions = array(IMAGETYPE_GIF => '.gif', IMAGETYPE_JPEG => '.jpg', IMAGETYPE_PNG => '.png');
$exifType = exif_imagetype($file['tmp_name']);
if (!isset($extensions[$exifType])) {
die('Unsupported file type');
}
$ext = $extensions[$exifType];
$targetDir = '/somewhere/else/';
do {
$target = $targetDir . uniqid() . $ext;
} while (file_exists($target));
if (!move_uploaded_file($file['tmp_name'], $target)) {
die('Something went wrong');
}
echo 'Yay, uploaded!';
Not that you should necessarily use that many die()
statements though, that's just for demonstration purposes.