避免需要花费很多时间的Apache

时间:2017-08-18 01:07:57

标签: php apache ddos

我正准备编写一个验证来自浏览器数据的类,其中一个方法验证了字符串的长度,然后出现了一些问题:如果有人发送一个包含2百万字符或更多字符的大字符串(或者其他什么) )?

如果我使用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以停止执行?

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

提前致谢!

1 个答案:

答案 0 :(得分:1)

您可以使用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的过滤器功能,例如:

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

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

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