How to check whether a variable in $_GET Array is

2019-01-19 07:47发布

I have a page like so:

http://sitename/gallery.php?page=2

It has pagination links at the bottom by which we can browse. Everytime the page numbers are clicked, it would send a GET request with parameters page=1 or page=2 and so on ...

When I store these values to $page from teh $_GET variable, it is a string value. I can convert it to an integer using (int) like this:

if(!empty($_GET['page'])){
       $page = (int)$_GET['page'];
       echo "Page Number: ".$page;
}

But how can I make sure that the value passed is an integer only and not other crap?

9条回答
霸刀☆藐视天下
2楼-- · 2019-01-19 08:21

Using filters:

if (null !== ($page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE))) {
    // $page is now an integer
}

This also checks whether the variable appears in the query string at the same time. If you want to differentiate between missing and invalid you have to leave off the last argument to filter_input():

$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
// $page can be null (not present), false (present but not valid) or a valid integer
查看更多
SAY GOODBYE
3楼-- · 2019-01-19 08:22

this is a way how to check parameter if it is intetger or not.

if (is_int((int) $_GET['user_id']) && (int) $_GET['user_id'] != 0) {
    $user_id = $_GET['user_id'];
}
查看更多
smile是对你的礼貌
4楼-- · 2019-01-19 08:22
if(!empty($_GET['page']) and is_numeric($_GET['page'])){
       $page = (int)$_GET['page'];
       echo "Page Number: ".$page;
}

is_numeric is probably what you need.

查看更多
别忘想泡老子
5楼-- · 2019-01-19 08:22
if (isset($_GET['page']) && (($get_page_filtered = filter_var($_GET['page'], FILTER_VALIDATE_INT)) !== FALSE) {
  $get_page_int = $get_page_filtered;
}

@see https://stackoverflow.com/a/41868665/6758130

查看更多
The star\"
6楼-- · 2019-01-19 08:26

You can also check with

isNAN($_GET['something']);//is_numeric($_GET['something'])

it returns a boolean value(true,flase)....if its true then it is not an integer,if false its an integer.

查看更多
可以哭但决不认输i
7楼-- · 2019-01-19 08:31

Using is_int won't help, probably. All incoming parameters (including $_GET and $_POST) are parsed as strings by PHP. The is_int function checks the datatype, not the value. ctype_digit checks for only digits though:

if(isset($_GET['page']) && ctype_digit($_GET['page']){
   $page = (int)$_GET['page'];
   echo "Page Number: ".$page;
}
查看更多
登录 后发表回答