PHPのお勉強!

PHP TOP

Filter 関数

目次

  • filter_has_var — 指定した型の変数が存在するかどうかを調べる
  • filter_id — フィルタの名前からフィルタ ID を返す
  • filter_input — 指定した名前の変数を外部から受け取り、オプションでそれをフィルタリングする
  • filter_input_array — 外部から変数を受け取り、オプションでそれらをフィルタリングする
  • filter_list — サポートされるフィルタの一覧を返す
  • filter_var — 指定したフィルタでデータをフィルタリングする
  • filter_var_array — 複数の変数を受け取り、オプションでそれらをフィルタリングする
add a note

User Contributed Notes 4 notes

up
3
vojtech at x dot cz
17 years ago
Also notice that filter functions are using only the original variable values passed to the script even if you change the value in super global variable ($_GET, $_POST, ...) later in the script.

<?php
echo filter_input(INPUT_GET, 'var'); // print 'something'
echo $_GET['var']; // print 'something'
$_GET['var'] = 'changed';
echo
filter_input(INPUT_GET, 'var'); // print 'something'
echo $_GET['var']; // print 'changed'
?>

In fact, external data are duplicated in SAPI before the script is processed and filter functions don't use super globals anymore (as explained in Filter tutorial bellow, section 'How does it work?').
up
0
fumble1 at web dot de
17 years ago
I recommend you to use the FILTER_REQUIRE_SCALAR (or FILTER_REQUIRE_ARRAY) flags, since you can use array-brackets both to access string offsets and array-element -- however, not only this can lead to unexpected behaviour. Look at this example:

<?php
$image
= basename(filter_input(INPUT_GET, 'src', FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW));
// further checks
?>

/script.php?src[0]=foobar will cause a warning. :-(
Hence my recommendation:

<?php
$image
= basename(filter_input(INPUT_GET, 'src', FILTER_UNSAFE_RAW, FILTER_REQUIRE_SCALAR | FILTER_FLAG_STRIP_LOW));
// further checks
?>
up
-1
vojtech at x dot cz
17 years ago
Just to note that "server and env support may not work in all sapi, for filter 0.11.0 or php 5.2.0" as mentioned in Filter tutorial bellow.

The workaround is obvious:
Instead of
<?php
$var
= filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_DEFAULT);
?>
use
<?php
$var
= filter_var(isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : NULL, FILTER_DEFAULT);
?>
up
-5
Richard Davey rich at corephp dot co dot uk
17 years ago
There is an undocumented filter flag for FILTER_VALIDATE_BOOLEAN. The documentation implies that it will return NULL if the value doesn't match the allowed true/false values. However this doesn't happen unless you give it the FILTER_NULL_ON_FAILURE flag like this:

<?php
$value
= 'car';
$result = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
?>

In the above $result will equal NULL. Without the extra flag it would equal FALSE, which isn't usually a desired result for this specific filter.
To Top