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



我正要编写一个验证来自浏览器的数据的类,其中一个方法验证字符串的长度,然后我想到了一件事:如果有人发送一个包含 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(( 是个好主意吗?

有没有另一种方法可以做到这一点,例如配置 APACHE 以在服务器处理请求超过 X 秒时停止执行?

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

提前感谢!

您可以使用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['content'] 不是由字母、数字、下划线或连字符组成,并且长度不介于 1 到 64 个字符之间,则不接受。

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

最新更新