EBrown has a good answer already, where he shows which steps has to be taken to make sure the page number is set correctly. He also comes up with a handy function. Let me show you another approach, using build-in functionality in PHP to handle the given problem.
Filter the input
Make use of PHPs filter_input:
$page_number = filter_input(INPUT_GET, 'page_number', FILTER_VALIDATE_INT);
It uses a predefined validation filter called FILTER_VALIDATE_INT, that …
… validates value as integer, optionally from the specified range, and converts to int on success.
So $page_number will be of type int and not string in case of success. If the filter fails, $page_name will be null|false:
Value of the requested variable on success, FALSE if the filter fails, or NULL if the variable_name variable is not set. If the flag FILTER_NULL_ON_FAILURE is used, it returns FALSE if the variable is not set and NULL if the filter fails.
Should I always default to 1?
Like in your question, if $page_number is not set at all, you should set it to 1. Using filter_input as described before you can test this case like:
if (null === $page_number) {
$page_number = 1;
}
But there are more cases to be handled like:
- invalid values, like
-1|0|10000001
- other non-integer values, like
hello-world|a4fe|1.2
I recommend to not to default to 1 in any of these cases, but to show a 404 error page instead.
To make sure the integer value of $page_number will produce a valid page, you can take it one step further and set a range for the filter. The complete example would look like
$page_number = filter_input(
INPUT_GET,
'page_number',
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1, 'max_range' => 104]]
);
if (false === $page_number) {
// show 404 page
}
if (null === $page_number) {
$page_number = 1;
}
1 Unless you have 1000000 or more pages of course.