Codeigniter - How to get url variable value inside contoller function?

依然范特西╮ 提交于 2019-12-21 02:57:13

问题


I have URL like this: http://localhost/sitename/some-post-title/code=24639204963309423

Now I have one findUser function in my controller file

public function findUser() {
   // I have tried with $_GET['code']
}

and I am trying to get code variable value inside this function. I have tried with $_GET['code'] but did not worked.

Any Idea how to get value inside controller function?

Thanks.


回答1:


Are you trying to get a path segment variable or a GET variable? It looks like you're going for a bit of both.

Natively in CI, you can use $this->input->get if you update your url to look more like

http://localhost/sitename/some-post-title/?code=24639204963309423

(Note the question mark).

Alternatively, you can modify your URL to look like this

http://localhost/sitename/some-post-title/code/24639204963309423

And then use URI segments like so

$data = $this->uri->uri_to_assoc();
$code = $data['code'];

If you do not want to change your URL, you will have to break that string up manually like so

$data = $this->uri->segment(3);
$data = explode($data, '=');
$code = $data[1];

I would argue the second option is the most SEO-friendly and pretty solution. But each of these should be functionally identical.




回答2:


If your URI contains more then two segments they will be passed to your function as parameters.

For example, lets say you have a URI like this:

example.com/index.php/products/shoes/sandals/123

Your function will be passed URI segments 3 and 4 ("sandals" and "123"):

<?php
class Products extends CI_Controller {

    public function shoes($sandals, $id)
    {
        echo $sandals;
        echo $id;
    }
}
?> 

If you are using GET to get parameters, you can do like this:

$this->input->get('get_parameter_name'); 

Typically there is a one-to-one relationship between a URL string and its corresponding controller class/method. The segments in a URI normally follow this pattern:

example.com/class/function/id/

More details for Controllers find here and for GET find here



来源:https://stackoverflow.com/questions/32569642/codeigniter-how-to-get-url-variable-value-inside-contoller-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!