如何检查$ _GET数组中的变量是否是整数? [英] How to check whether a variable in $_GET Array is an integer?

查看:110
本文介绍了如何检查$ _GET数组中的变量是否是整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的一个页面:


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


我们可以浏览底部的分页链接。每次点击页码时,它都会发送带有 page = 1 page = 2 参数的GET请求,等等......



当我将这些值从 $ _ GET 变量存储到 $ page 时,它是一个字符串值。我可以像下面这样使用(int)将它转换为整数:

  if(!empty($ _ GET ['page'])){
$ page =(int)$ _ GET ['page'];
echoPage Number:。$ page;
}

但是,如何确保传递的值是 integer only 而不是其他废话?

解决方案

b
$ b

  if(null!==($ page = filter_input(INPUT_GET,'page',FILTER_VALIDATE_INT,FILTER_NULL_ON_FAILURE))){
// $ page现在是一个整数
}

这也检查变量是否出现在查询中字符串在同一时间。如果你想区分失踪和失效,你必须抛弃最后一个参数到 filter_input()

  $ page = filter_input(INPUT_GET,'page',FILTER_VALIDATE_INT); 
// $ page可以为null(不存在),false(存在但无效)或有效整数


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?

解决方案

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

这篇关于如何检查$ _GET数组中的变量是否是整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆