Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP check if variable from $_GET is integer

Tags:

php

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');
        }
    }
like image 766
Peter Bushnell Avatar asked Nov 11 '15 12:11

Peter Bushnell


2 Answers

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:

  • if $_GET['id'] is not set at all:
    • error 400, bad request
  • else fetch database record with given id, not caring at all what the id looks like (but be aware of what invalid values might cast to and whether you might need to care about that after all)
    • if no record found:
      • error 404, not found
    • else:
      • display page

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;
like image 60
deceze Avatar answered Oct 17 '22 12:10

deceze


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
}
like image 28
fabpico Avatar answered Oct 17 '22 11:10

fabpico