繁体   English   中英

防止以图片上传形式上传大型且不受支持的文件

[英]prevent uploading of large and unsupported files in image upload form

我有一个带有图像上传选项的php表单,如下所示

 <input type="hidden" name="old_picture" value="<?php if (!empty($old_picture)) echo        $old_picture; ?>" />
  <label for="new_picture">Picture:</label>
  <input type="file" id="new_picture" name="new_picture" />

和PHP脚本类似

if (!empty($new_picture)) {
  if ((($new_picture_type == 'image/gif') || ($new_picture_type == 'image/jpeg') || ($new_picture_type == 'image/pjpeg') ||
    ($new_picture_type == 'image/png')) && ($new_picture_size > 0) && ($new_picture_size <= MM_MAXFILESIZE) &&
    ($new_picture_width <= MM_MAXIMGWIDTH) && ($new_picture_height <= MM_MAXIMGHEIGHT)) {
    if ($_FILES['file']['error'] == 0) {
      // Move the file to the target upload folder
      $target = MM_UPLOADPATH . basename($new_picture);
      if (move_uploaded_file($_FILES['new_picture']['tmp_name'], $target)) {
        // The new picture file move was successful, now make sure any old picture is deleted
        if (!empty($old_picture) && ($old_picture != $new_picture)) {
          @unlink(MM_UPLOADPATH . $old_picture);
        }
      }
      else {
        // The new picture file move failed, so delete the temporary file and set the error flag
        @unlink($_FILES['new_picture']['tmp_name']);
        $error = true;
        echo '<p class="error">Sorry, there was a problem uploading your picture.</p>';
      }
    }
  }
  else {
    // The new picture file is not valid, so delete the temporary file and set the error flag
    @unlink($_FILES['new_picture']['tmp_name']);
    $error = true;
    echo '<p class="error">Your picture must be a GIF, JPEG, or PNG image file no greater than ' . (MM_MAXFILESIZE / 1024) .
      ' KB and ' . MM_MAXIMGWIDTH . 'x' . MM_MAXIMGHEIGHT . ' pixels in size.</p>';
  }
}

一切正常,但是当作为测试我尝试上载.zip文件时,发生了问题,图像未加载但刷新了数据库。 该用户的所有条目均被删除。

现在我想要一些关于如何防止这种情况的建议

提前致谢

在客户端,您实际上可以依靠的工作量不多。 但这可以帮助防止意外问题。

将此属性添加到文件上传控件以限制文件类型: accept="image/gif, image/jpeg"

如果您想确定自己所得到的,验证需要在服务器端进行。

检查$_FILES['uploadctl']['size']的文件大小,看看它是否超出了您的限制。

您可以通过在php.ini中设置upload_max_filesize来强制php限制可接受的文件上传大小。 缺省值很低。

您不能真正相信上载文件的扩展名实际上是正确的。 仅仅因为它说.jpg并不意味着它真的是。 如果您只接受图像,则应该能够使用getimagesize()验证getimagesize() 如果您接受更大范围的文件,请使用Fileinfo检查文件。

如果删除了数据库中的条目,则可能是您在此处未显示的代码中存在逻辑问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM