dongyingla8668 2017-10-04 02:20
浏览 24
已采纳

检查是否使用参数调用函数

Codeigniter has a syntax for url parameter passing for functions inside the controller.

If a function for example:

function index($id){
     $this->model->get_user($id);
}

Assuming that this function is called without supplying the ID namely called as

ProjectName/Controller/index

it will return an error as it expects a parameter. Is there a way to check if a parameter exists.

  • 写回答

1条回答 默认 最新

  • dpmfur2635 2017-10-04 03:26
    关注

    No there is not a way to check if one exists per-say as that error happens before the controller has a chance to run code. ie. before the class method executes.

    That said there is a simple workaround for this: You can supply a default value and check for that for example

    function index($id = null){
         if( is_null($id) ){
              ///do something - like show a pretty error, or redirect etc...
         }else{
            $this->model->get_user($id);
         }
    }
    

    This way when no parameter is supplied the ID will be null, this is fairly safe ( when using null ) because you can never supply null as part of the url path even doing this

       www.mysite.com/index/null  //or however the url works out in your case
    

    Will supply null as a string, because everything in the url comes through as a string. So 'null' as a string is not in fact null it's just the word null. If that makes sense. So given that null could never be supplied and only happens if no other value is supplied.

    In this case it may be worth casting the input to a int or further checking if it's an improper value.

    This could be done several ways:

    Casting:

      function index($id = null){
         if( is_null($id) ){
              ///do something - like show a pretty error, or redirect etc...
         }else{
            $this->model->get_user((int)$id);
            //cast to int, things that are not INT or string equivalents become 0, which should not find a user as it would look for ID = 0
         }
    }
    

    By Regx check:

    function index($id = null){
         if( is_null($id) ){
              ///do something - like show a pretty error, or redirect etc...
        }else if( preg_match('/^[^\d]+$/', $id )){
             // not an int ( contains anything other than a digit )
        }else{
            $this->model->get_user($id);
         }
    }
    

    Cheers.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题