避免花费大量时间的请求 Apache

Avoid requests that take much time Apache

我正要编写一个 class 来验证来自浏览器的数据,其中一种方法验证字符串的长度,然后我想到了一些事情:如果有人发送一个非常大的字符串,其中有 200 万字符或更多(或其他)?

如果我使用 strlen() 来计算字节数,它将计算到最后一个字节。 计算所有这些字节是一种浪费。

想了想,做了这样的:

   Class Validator
    {
     static public function verify_str_length($str, $min, $max)
     {   
       $i;
       $counter = $min;
       $msg = "";
      // looling until null char is found
      //
       for($i=$min-1;$i<$max;$i++) {
          if(!isset($str[$i])) {
            if($i == ($min -1)) {
                // if first iteration
                // we find the null char so early.
                // $i starts with the minimum length allowed, the string
                // length is lower than that so it is too short
                $msg = 'Too short string';
                return -1;
            }
             return 0;
         }

      }
       if(isset($str[$i])) {
         // if we reach the max and keep without finding the null char so
         // the string length is higher than $max
          $msg = 'Too long string';
           return 1;
      }
       return 0;
       }
      //
    /*  Others Methods 
         ..... */
   }

请注意,我不需要字符串中的字符数,只要它高于 $min 且低于 $max 即可。我将丢弃所有其他字符。

我的问题是:这样做而不是使用 strlen() 是个好主意吗?

是否有另一种方法可以做到这一点,例如如果服务器处理请求的时间超过 X 秒,则将 APACHE 配置为停止执行?

或者我可以同时使用这两个选项吗?

提前致谢!

您可以使用 PHP 的 post_max_size 指令来限制提交内容的数量。请谨慎使用此设置,因为如果您有文件上传,它们也必须适合此大小。

http://php.net/manual/en/ini.core.php#ini.post-max-size

要限制解析输入数据所花费的时间,您可以使用max_input_time

http://php.net/manual/en/info.configuration.php#ini.max-input-time

要限制执行时间,请使用max_execution_time

http://php.net/manual/en/info.configuration.php#ini.max-execution-time

您可以在 .htaccess 中设置这些,如下所示:

php_value post_max_size 1M
php_value max_execution_time 30
php_value max_input_time 5

为了验证,您应该使用 PHP 的 filter 函数,例如:

$content = filter_input( INPUT_POST, 'content', FILTER_VALIDATE_REGEXP, [ 'options' => ['regexp' => '/^[\w-]{1,64}$/']] );

这将确保如果 $_POST['content'] 不是由字母、数字、下划线或连字符组成,并且长度不在 1 到 64 个字符之间,则不会被接受。

http://php.net/manual/en/function.filter-input.php