php图像类型检测

时间:2011-05-20 02:42:20

标签: php

无法检测mime类型。如果我删除($mime=="image/jpeg" || $mime=="image/pjpeg"),则可以成功上传图片。

$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;
        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";
}

1 个答案:

答案 0 :(得分:1)

上传文件的nametype信息应视为完全信息化且永远不会用于任何严重的,因为它是用户提供的信息,很容易被欺骗。您应该只查看tmp_nameerrorsize字段,以确定是否要接受文件。要查找文件的实际MIME类型,请使用PHP的内置函数:

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!';

不是说你应该使用那么多die()语句,这只是为了演示目的。