2015-06-21 65 views
0

我的问题很简单。我不应该让用户上传图像,而是从源代码创建图像时,是否应该在验证中进行彻底检查?使用PHP上传图片与从上传图片创建图片时的验证过程

我在想,我只会用$_FILES['file']['tmp_name']用PHP创建功能的新的JPEG或PNG图像。

在php.net,我发现这个建议得票最多,我应该做这样还是矫枉过正?

try { 

    // Undefined | Multiple Files | $_FILES Corruption Attack 
    // If this request falls under any of them, treat it invalid. 
    if (
     !isset($_FILES['upfile']['error']) || 
     is_array($_FILES['upfile']['error']) 
    ) { 
     throw new RuntimeException('Invalid parameters.'); 
    } 

    // Check $_FILES['upfile']['error'] value. 
    switch ($_FILES['upfile']['error']) { 
     case UPLOAD_ERR_OK: 
      break; 
     case UPLOAD_ERR_NO_FILE: 
      throw new RuntimeException('No file sent.'); 
     case UPLOAD_ERR_INI_SIZE: 
     case UPLOAD_ERR_FORM_SIZE: 
      throw new RuntimeException('Exceeded filesize limit.'); 
     default: 
      throw new RuntimeException('Unknown errors.'); 
    } 

    // You should also check filesize here. 
    if ($_FILES['upfile']['size'] > 1000000) { 
     throw new RuntimeException('Exceeded filesize limit.'); 
    } 

    // DO NOT TRUST $_FILES['upfile']['mime'] VALUE !! 
    // Check MIME Type by yourself. 
    $finfo = new finfo(FILEINFO_MIME_TYPE); 
    if (false === $ext = array_search(
     $finfo->file($_FILES['upfile']['tmp_name']), 
     array(
      'jpg' => 'image/jpeg', 
      'png' => 'image/png', 
      'gif' => 'image/gif', 
     ), 
     true 
    )) { 
     throw new RuntimeException('Invalid file format.'); 
    } 

    // You should name it uniquely. 
    // DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !! 
    // On this example, obtain safe unique name from its binary data. 
    if (!move_uploaded_file(
     $_FILES['upfile']['tmp_name'], 
     sprintf('./uploads/%s.%s', 
      sha1_file($_FILES['upfile']['tmp_name']), 
      $ext 
     ) 
    )) { 
     throw new RuntimeException('Failed to move uploaded file.'); 
    } 

    echo 'File is uploaded successfully.'; 

} catch (RuntimeException $e) { 
    echo $e->getMessage(); 
} 

回答

0

我认为你应该这样做(你是那样彻底的验证).Reasons

  • 如果什么人上传有害的PHP文件?

  • 如果什么人上传大尺寸文件?

  • 其他安全问题


的验证如此彻底是必要的,否则这将是需要验证site.The时间的危险是less.So安全是最重要的。

您在php.net上获得的代码验证文件大小,扩展等,这是完美的,并最大限度地降低风险。

也是从源头创建图像需要更多的resources.So让用户在验证上传图片和深入是最好的。 :)

+0

感谢您的回答。但它似乎在这里不同意你的答案:http://stackoverflow.com/questions/15595592/php-validating-the-file-upload。 “唯一可靠的图像验证方法是使用GD或Imagick制作它的副本”因此,您不应让用户上传图像以节省资源。或者我错了? – Alex