2017-08-18 6 views
0

私はブラウザからのデータを検証するクラスを作成しようとしていましたが、それらのメソッドの1つが文字列の長さを検証すると、何かが私の頭に浮かんできました:誰かが2百万文字以上のもの(何でも)?多くの時間を要するリクエストを避けるApache

バイト数をカウントするためにstrlen()を使用すると、最後のバイト数がカウントされます。 これらすべてのバイトを数えるのは無駄でしょう。

しばらく考えた後、私はこのような何か作っ:私はそれが$ minよりも高いと$ maxよりも小さい場合には、文字列の文字数を必要としない

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 
     ..... */ 
    } 

注意を。私は他のすべての文字を破棄します。

私の質問です:strlen()を使用する代わりにそうすることをお勧めしますか?

サーバーが要求の処理にX秒以上かかる場合、実行を停止するようにconfigurate APACHEのようにこれを行う別の方法はありますか?

どちらのオプションも使用できますか?

ありがとうございます!

+0

いいえstrlenを使用してください。 – user2182349

+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 ['content']が文字、数字、下線またはハイフンで構成されていなくて、1つの長さは64文字ですが、受け入れられません。

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

関連する問題