Need an explanation on this.. I'm adding pagination to a website, and need a pointer on Filter Input/Escape Output. As you can see below, the newly created page
global defaults to page 1 when the page first loads, and this is the correct behavior, using the shorthand ternary operator.
$itemsPerPage = 20;
$numOfFilms = $totalRows->rows;
$numOfPages = ceil($numOfFilms / $itemsPerPage);
$filter ='page';
$getPages = isset($_GET[$filter])
? $_GET[$filter]
: 1;
var_dump($getPages); // <-- Testing
$paginationOptions = [
'options' => [
'default' => 1,
'min_range' => 1,
'max_range' => $numOfPages,
]
];
$pageNumberClean = trim($getPages);
$pageNumber = filter_var(
$pageNumberClean,
FILTER_VALIDATE_INT,
$paginationOptions
);
$range = $itemsPerPage * ($pageNumber - 1);
Knowing that I should never trust user input, and in turn the reason Netbeans throws a Warning:
Do not Access the Superglobal _GET Array directly. Use some filtering functions instead...
If I wrap both sides of the ternary statement in filter_input
the warning goes away and is syntactically correct, but the page will not run, because the filtered input variable page
doesn't exist in the _GET array, so:
What is the accepted standard or proper way to create a _GET array variable without directly accessing the _GET array?
In other words: Can I properly use
filter_input
and create the variable, so the warning goes away?
Telling me to turn the warning off is not the answer I'm looking for.
Also, note that I've googled for "How to initialize a _GET variable" and most of the results explain the difference between $_GET
and $_POST
which I already know.
Thanks for your time
Here's a solution that should satisfy NetBeans, because it uses one of PHP's filter functions. As I mentioned in a comment, I would consider "is_int()" to be a safe enough check to use here as well.
According to the PHP Docs in the following places, this will remove all non-integer characters from the GET variable. We then check to make sure the remaining string isn't empty (either blank, false, or 0).
Please note: a page number of 0 will trigger the empty, and return 1. Let me know if this is an issue.
https://secure.php.net/manual/en/function.empty.php https://secure.php.net/manual/en/function.filter-input.php https://secure.php.net/manual/en/filter.filters.sanitize.php
https://php.net/manual/en/function.is-int.php
Extra Note: You could also do this with arguments to the filter function, including a default value. That way you could do it all with two lines cleanly: