Search code examples
phpnetbeansfilterfilteringsuperglobals

How do I apply filter_input to superglobals


According to netbeans IDE, I need to add some sort of a filter to superglobals, filter_input() suggested by netbeans, for the code below

$page = (isset($_GET['p']) && !empty($_GET['p'])) ? $_GET['p']: 'home';

After researching, I found this example on stackoverflow

$name = ($name = filter_input(INPUT_GET, 'name')) ? $name : 'default_value';

But I fail to understand how to apply this to the code above.

Original Code, just in case you need to see.

$page = (isset($_GET['p']) && !empty($_GET['p'])) ? $_GET['p']: 'home';
$page = htmlspecialchars($page, ENT_QUOTES, 'UTF-8');
$page = preg_replace('/[^-a-zA-Z0-9_]/', '', $page);

Solution

  • Netbeans IDE is trying to have you be safe with your variable handling for GLOBALS. Because these can be set by unknown sources, it wants you to try and attempt to validate or sanitize these when applying them to a variable. There are several methods which make your life easier here (For example, you can potentially use FILTER_SANITIZE_FULL_SPECIAL_CHARS instead of your second line of code.) Because you're doing a preg_replace function on your $page, I'd say it's pretty safe to leave as is, although if you wanted to remove the warning, this should work, but it's functionally identical. See this post for more info.

    $page = ($page = filter_input(INPUT_GET, 'p')) ? $page : 'home';
    $page = htmlspecialchars($page, ENT_QUOTES, 'UTF-8');
    $page = preg_replace('/[^-a-zA-Z0-9_]/', '', $page);