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.

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

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法