Php 避免花费大量时间的请求
我正要编写一个类来验证来自浏览器的数据,其中一个方法验证字符串的长度,然后我想到了一个问题:如果有人发送一个包含200万或更多字符的非常大的字符串,或者其他什么 如果我使用strlen来计数字节,它将计数到最后一个字节。 计算所有这些字节将是一种浪费 想了一会儿,我做了这样的事情:Php 避免花费大量时间的请求,php,apache,ddos,Php,Apache,Ddos,我正要编写一个类来验证来自浏览器的数据,其中一个方法验证字符串的长度,然后我想到了一个问题:如果有人发送一个包含200万或更多字符的非常大的字符串,或者其他什么 如果我使用strlen来计数字节,它将计数到最后一个字节。 计算所有这些字节将是一种浪费 想了一会儿,我做了这样的事情: Class Validator { static public function verify_str_length($str, $min, $max) { $i
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指令来限制提交的内容量。请注意此设置,因为如果上载了文件,它们也必须符合此大小
要限制解析输入数据所花费的时间,可以使用max_input_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个字符之间,则不接受它
不,请使用strlen。谢谢您的回复。如何避免计算不必要的字节?