The solution below is what I have cooked up to check that a variable from $_GET is an integer. It seems a bit convoluted and I am sure that there must be a simpler solution. The error array is used to show the user messages.
// Create array to hold errors
$errors = array();
// Get ID from URL
$user_id = isset($_GET['id']) ? $_GET['id'] : '';
// Check for empty ID
if (empty($user_id)) {
array_push($errors, 'Empty user ID');
} else {
// Check if ID is numeric
if (!is_numeric($user_id)) {
array_push($errors, 'Invalid user ID');
} else {
// Get numerical value of string (int or float)
$num_user_id = $user_id + 0;
// Check that number is an int
if (!is_integer($num_user_id))
array_push($errors, 'Invalid user ID');
}
}
if (!isset($_GET['id'])) {
$errors[] = 'Empty user id';
} else if (!ctype_digit($_GET['id'])) {
$errors[] = 'Invalid id';
} else {
$num_user_id = (int)$_GET['id'];
}
That covers all possibilities: not set and not numeric.
That is if you need to differentiate your error messages between not set and not numeric. Otherwise filter_input
is something you should look at.
Arguably you should probably be more relaxed about the specific invalidity; an invalid id is an invalid id and it hardly matters why it's invalid. There are more reasons why an id could be invalid than why it is valid. Caring about all of these reasons individually is not necessarily worth the effort.
I'm assuming that you're fetching a user record from a database with this id; your error control should probably more follow this logic:
$_GET['id']
is not set at all:
To that extend, filter_input
is perfect:
if (!$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT)) {
header("HTTP/1.0 400 Bad Request");
exit;
}
if (!$user = get_user_record($id)) {
header('HTTP/1.0 404 Not Found');
exit;
}
echo $user;
You can cast your incoming GET with (int)
. Then when this number is greater than 0
, it was already a valid number.
<?php
$user_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if(0 < $user_id) {
// Do your foo and bars
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With