douyun8674 2012-08-30 09:51
浏览 50
已采纳

如何检查$ _GET数组中的变量是否为整数?

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条回答 默认 最新

  • doudu8291 2012-08-30 09:59
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型