【问题标题】:PHP Warning: POST Content-Length of n bytes exceeds the limit of 3145728 bytes in Unknown on line 0PHP 警告:POST Content-Length of n 字节超出了 Unknown on line 0 中 3145728 字节的限制
【发布时间】:2012-07-29 03:37:28
【问题描述】:

我很惊讶在我的错误日志中发现了上述错误,因为我认为我已经完成了必要的工作来捕获我的 PHP 脚本中的错误:

if ($_FILES['image']['error'] == 0)
{
 // go ahead to process the image file
}
else
{
 // determine the error
 switch($_FILES['image']['error'])
 {
  case "1":
  $msg = "Uploaded file exceeds the upload_max_filesize directive in php.ini.";
  break;
  ....
 }
}

在我的 PHP.ini 脚本中,相关设置为:

memory_limit = 128M
post_max_size = 3M
upload_max_filesize = 500K

我知道 3M 相当于 3145728 字节,这就是触发错误的原因。如果文件大小在 500k 以上但小于 3M,则 PHP 脚本将能够正常运行,并按照 case 1$msg 中发出错误消息。

当帖子大小超过post_max_size 但仍在内存限制范围内时,我如何捕捉此错误,而不是让脚本突然终止并发出 PHP 警告?我看过类似的问题hereherehere,但找不到答案。

【问题讨论】:

  • 你为什么不把你的函数包装在一个try..catch 块中?
  • error_reporting(E_ALL & ~E_WARNING); 关闭 PHP 警告。
  • @fdomig 这应该是绝对的最后手段。
  • @fdomig 在生产系统上是的。但现在 OP 正在开发中,此时应该努力避免变通方法。
  • @MichaelRobinson 一个解决方案是为您自己的错误处理程序提供如下内容:stackoverflow.com/a/1241751/246051

标签: php


【解决方案1】:

找到了一个不直接处理错误的替代解决方案。以下代码由软件工程师 Andrew Curioso 在其blog 中编写:

if($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) &&
     empty($_FILES) && $_SERVER['CONTENT_LENGTH'] > 0)
{
  $displayMaxSize = ini_get('post_max_size');

  switch(substr($displayMaxSize,-1))
  {
    case 'G':
      $displayMaxSize = $displayMaxSize * 1024;
    case 'M':
      $displayMaxSize = $displayMaxSize * 1024;
    case 'K':
       $displayMaxSize = $displayMaxSize * 1024;
  }

  $error = 'Posted data is too large. '.
           $_SERVER[CONTENT_LENGTH].
           ' bytes exceeds the maximum size of '.
           $displayMaxSize.' bytes.';
}

正如他的文章中解释的那样,当帖子大小超过post_max_size时,$_POST$_FILES的超全局数组将变为空。因此,通过对这些进行测试,并确认有一些内容是使用 POST 方法发送的,就可以推断出发生了这样的错误。

其实有一个类似的问题here,之前没找到。

【讨论】:

    【解决方案2】:

    您可以在上传之前先用 javascript 检查它吗?

    // Assumed input for file in your HTML
    <input type="file" id="myFile" />
    
    
    //binds to onchange event of your input field
    $('#myFile').bind('change', function() {
        alert(this.files[0].size);
    });
    

    你也可以在它周围弹出一个 try catch:

    try 
    {
        if (!move_uploaded_file( 'blah blah' )) 
        {
            throw new Exception('Too damn big.');
        }
        // Can do your other error checking here...
        echo "Upload Complete!";
    } 
    catch (Exception $e) 
    {
        die ('File did not upload: ' . $e->getMessage());
    }
    

    【讨论】:

    • 用户可能没有启用javascript。
    • +1 这可能不能完全解决问题,但是一个很好的建议。
    • @QuestionOverflow 虽然是真的,但发生这种情况的可能性是百万分之一,因为今天的一切都需要启用 JS。很难找到禁用 JS 的人
    • @阿司匹林,我明白了。但我正在寻找更可靠的服务器端解决方案。您不想只在客户端进行表单验证,对吗?
    • 是的,我可以采用 try 和 catch 块,但这是要走的路吗?因为我认为异常是由于糟糕的编码而触发的,我想避免糟糕的编码。
    猜你喜欢
    • 2020-12-04
    • 2013-06-20
    • 2012-10-14
    • 1970-01-01
    • 2019-10-15
    • 2011-09-10
    • 2016-07-15
    • 2011-09-13
    相关资源
    最近更新 更多