看板 Knuckles_note
作者 標題 [PHP] 使用 filter_input 取代 $_GET, $_POST, $_SERVER
時間 2015-06-02 Tue. 17:33:26
傳統用來取得網址參數的方法是用 $_GET['xxx']
可以改用比較安全的 filter_input()
參考: http://php.net/manual/en/function.filter-input.php
filter_input( int $type, string $variable_name )
$type 可以為 INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, INPUT_ENV例如取代 $xxx = $_GET['xxx']; 的用法為
$xxx = filter_input(INPUT_GET,'xxx');
若變數不存在會回傳 null
要加上 filter 選項的話,使用
filter_input( int $type, string $variable_name, int $filter = FILTER_DEFAULT, mixed $options )
可指定要用的 filter 類型和 filter 的 options
可用的 filter 可參考 http://php.net/manual/en/filter.filters.php
若 filter 不符合會回傳 false
例如要取得整數的話,使用
$xxx = filter_input(INPUT_GET,'xxx', FILTER_VALIDATE_INT);
要使用 FILTER_VALIDATE_INT 的 $options 的話,使用
$options = ['options'=>['default'=>0, 'min_range'=>0, 'max_range'=>9] ];
$xxx = filter_input(INPUT_GET,'xxx', FILTER_VALIDATE_INT, $options);
可將數字限制在 0~9,若超過的話輸出 0$xxx = filter_input(INPUT_GET,'xxx', FILTER_VALIDATE_INT, $options);
要使用正規表示式的話,使用
$options = ['options'=>['default'=>'', 'regexp'=>"/^\w*$/"] ];
$xxx = filter_input(INPUT_GET,'xxx', FILTER_VALIDATE_REGEXP, $options);
可限制為字母與數字,不符合的話輸出 ''$xxx = filter_input(INPUT_GET,'xxx', FILTER_VALIDATE_REGEXP, $options);
要使用自己寫的 callback function 來過濾的話,使用
function my_filter($value){
return $value;
}
filter_input(INPUT_GET, 'xxx', FILTER_CALLBACK, ['options' => 'my_filter']);
return $value;
}
filter_input(INPUT_GET, 'xxx', FILTER_CALLBACK, ['options' => 'my_filter']);
◎ 備註
參考: http://php.net/manual/en/function.filter-input.php#77307
INPUT_SERVER 在 fastcgi 時可能會有問題
$_SERVER 的值還是用 $_SERVER 來取就好了
--
※ 作者: Knuckles 時間: 2015-06-02 17:33:26
※ 編輯: Knuckles 時間: 2015-10-19 11:51:07
※ 看板: KnucklesNote 文章推薦值: 0 目前人氣: 0 累積人氣: 2332
回列表(←)
分享