php image type detection
Unable to detect mime type. if I remove ($mime=="image/jpeg" || $mime=="image/pjpeg")
, it could upload the image successfully.
$mime = $_FILES['Filedata']['type'];
if((!empty($_FILES['Filedata']['tmp_name'])) && ($_FILES['Filedata']['error'] == 0)) {
$filename = basename($_FILES['Filedata']['name']);
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if (($ext=="jpg" || $ext=="jpeg") && ($mime=="image/jpeg" || $mime=="image/pjpeg") && ($_FILES["Filedata"]["size"] < 350000)) {
$newname = $filename;
开发者_StackOverflow if (!file_exists($newname)) {
if (move_uploaded_file($_FILES['Filedata']['tmp_name'], "./photo/" . $newname)) {
echo "It's done! The file has been saved as: ".$newname;
} else {
echo "Error: A problem occurred during file upload!";
}
} else {echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";}
} else {
echo "Error: Only .jpg images under 350Kb are accepted for upload";
}
} else {
echo "Error: No file uploaded";
}
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.
精彩评论