使用查询字符串时不返回 URI 段

URI segment does not get returned when using querystrings

我正在尝试对查询返回的搜索结果进行分页。我有以下 URL:

blog/search?query=post/5

我试图从 URL 中获取 $start=5 的值,使用:

$start = $this->uri->segment(3);

它没有返回任何东西。

删除 ?query=post,即 blog/search/5 可以正常工作。但是我想保留查询参数并读取值。

那是因为 URI 中的 ? 字符。 CodeIgniter URI 解析器(以及任何其他标准 URI 解析器)无法识别您的想法。在 ? 字符之后,都是查询字符串,而不是 URI 段。查看 PHP 的 parse_url() 的输出:

parse_url('blog/search?query=post/5')
[
    "path" => "blog/search",
    "query" => "query=post/5",
]

看到了吗?第一段是 blog,第二段是 search,其余是查询字符串。

您需要以标准方式更改您的 URI 设计。例如:

blog/search/5?query=post

这样对 $this->uri->segment(3) 的调用就会 return 您的想法。

谈到 CodeIgniter 分页库,请参阅 documentation 中的 reuse_query_stringpage_query_string 配置。