Codeigniter - 如何在控制器函数中获取 url 变量值?

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

我有 URL 这样的:http://localhost/sitename/some-post-title/code=24639204963309423

现在我的控制器文件中有一个 findUser 函数

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

并且我试图在该函数中获取 code 变量值。我试过 $_GET['code'] 但没有成功。

知道如何在控制器函数中获取值吗?

谢谢。

您是要获取路径段变量还是 GET 变量?看起来你两者兼而有之。

原生 CI,如果您将 url 更新为看起来更像

,则可以使用 $this->input->get
http://localhost/sitename/some-post-title/?code=24639204963309423

(注意问号)。

或者,您可以将 URL 修改为如下所示

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

然后像这样使用 URI 段

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

如果您不想更改 URL,则必须像这样手动拆分该字符串

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

我认为第二种选择是对 SEO 最友好且最漂亮的解决方案。但是它们中的每一个在功能上都应该是相同的。

如果您的 URI 包含两个以上的段,它们将作为参数传递给您的函数。

例如,假设您有这样一个 URI:

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

您的函数将传递 URI 段 3 和 4("sandals" 和“123”):

<?php
class Products extends CI_Controller {

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

如果你使用GET获取参数,你可以这样做:

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

通常 URL 字符串与其对应的控制器 class/method 之间存在一对一的关系。 URI 中的段通常遵循以下模式:

example.com/class/function/id/

有关控制器的更多详细信息,请查找 here and for GET find here