Hannibal Burr
Hannibal Burr

Reputation: 49

Only accept numbers as GET-variable

Hello,

I want to allow only numbers in $_GET method. I use this is in pagination to secure

$page = (isset($_GET['page']) && is_numeric($_GET['page']) ? (int) $_GET['page'] : 1);

If I enter special characters or alpha, it returns error

This should not be possible:

index.php?page=AA and index.php?page='!@#$%^&*()

Only this: index.php?page=1 or 2 ...

Anyone has a solution for this? :) thanks in advance...

Upvotes: 1

Views: 2708

Answers (4)

Dr.Molle
Dr.Molle

Reputation: 117314

I would suggest the use of filter_input()

$page= filter_input ( INPUT_GET, 
                      'page', 
                      FILTER_VALIDATE_INT,
                      array('options'=>array('min_range' => 1)));
if(!$page)$page=1;

Upvotes: 5

Chris
Chris

Reputation: 684

You've got a closing bracket in the wrong place - it should be:

$page = (isset($_GET['page']) && is_numeric($_GET['page'])) ? (int) $_GET['page'] : 1;

Upvotes: 0

Hossein
Hossein

Reputation: 4137

Convert it to number using intval then check it. If the value is not numeric, intval will return 0:

if (isset($_GET['page']))
    if (intval($_GET['page'] == 0)
        $page = 1;
    else
        $page = intval($_GET['page']);

or more compact:

$page = (isset($_GET['page']) && intval($_GET['page'] != 0) ? intval($_GET['page']) : 1;

Upvotes: 0

ComFreek
ComFreek

Reputation: 29424

I would just use intval() and a default value for $page:

$page = 1;

if ( isset($_GET['page']) )
  $page = intval($_GET['page']);

Upvotes: 0

Related Questions