I was about to programm a class that validates data from browsers and one of those methods validates length of strings, then something came to my mind: What if somebody sends a very big string with 2 millions of characters or more (or whatever) ?
If I use strlen() to count bytes, it will count to the last bytes. It would be a waste to count all those bytes.
After thinking for a while, I made something like this:
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
..... */
}
Note that I do not need the number of characters in the string, only if it higher than $min and lower than $max. I will discard all others chars.
My question is: would it be a good idea to do so instead of using strlen() ?
Is there another way to do this like configurate APACHE to stop execution if the server takes more than X seconds in processing the request ?
Or can I use both options?
Thanks in advance!