Trying to get a query string into a variable but only if it's an integer.
Code is probably a bit more complicated than it should be but this is where I'm up to-
//get page number. default is 1. check is not empty and is a number
if (empty($_GET['pag'])) {$page = 1;}
else if (is_int($_GET['pag'])){$page = $_GET['pag'];}
else {$page = 1;}
Where am I going wrong?
You probably want is_numeric()
instead - is_int()
doesn't test to see if a string is a numeric string.
if (empty($_GET['pag'])) {$page = 1;}
else if (is_numeric($_GET['pag'])){$page = (int) $_GET['pag'];}
else {$page = 1;}
I would suggest, type cast the value to an integer:
$page = empty($_GET['pag']) ? 1 : (int) $_GET['pag'];
Although, if I remember well, type casting something that is not an integer will make it a 0, but you should check anyways if the $page is in between bounds before doing anything with it, because the user might as well type in ?pag0 in your URL.
$page = ((isset($_GET['pag']) && is_numeric($_GET['pag'])) ? (int)$_GET['pag'] : 1;