图片上传php错误

时间:2015-08-10 12:11:30

标签: php mysqli

这是一个简单的php脚本,它将图像的扩展名检查为jpeg到png并且工作正常。问题是有人将任何其他文件重命名为.exe / .txt到jpeg,然后它会接受file.So我怎么能限制它即使重命名,如果它不是图像然后返回false。我可以应用像文件大小等限制,但任何人都可以否决它。我尝试了很多但没有帮助:

if(isset($_FILES['uploaded_file'])) {
    $errors     = array();
    $maxsize    = 2097152;
    $acceptable = array(
        'application/pdf',
        'image/jpeg',
        'image/jpg',
        'image/gif',
        'image/png'
    );

    if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
        $errors[] = 'File too large. File must be less than 2 megabytes.';
    }

    if(!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) {
        $errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
    }

    if(count($errors) === 0) {
        move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
    } else {
        foreach($errors as $error) {
            echo '<script>alert("'.$error.'");</script>';
        }

        die(); //Ensure no more processing is done
    }
}

2 个答案:

答案 0 :(得分:0)

使用finfo_file =&gt;见http://php.net/manual/de/function.finfo-file.php

if(isset($_FILES['uploaded_file'])) {
  $errors     = array();
  $maxsize    = 2097152;
  $acceptable = array(
    'application/pdf',
    'image/jpeg',
    'image/jpg',
    'image/gif',
    'image/png'
  );
  // CHECK FILE_TYPE
  $finfo = finfo_open(FILEINFO_MIME_TYPE); 
  $type = finfo_file($finfo, $_FILES['uploaded_file']) ;
  // DEV-INFO
  echo $type; die;
  // ....

}

答案 1 :(得分:0)

尝试使用getimagesize()函数。它将确定任何GIF,JPG,PNG,XBM或WBMP图像文件的大小。如果它不是有效图片,getimagesize()将返回FALSE