Jaydeep Goswami Jaydeep Goswami - 7 days ago 7
PHP Question

URI segment does not get returned when using querystrings

I'm trying to paginate the search results returned by the query. I have the following URL:

blog/search?query=post/5


Where I am trying to get the value of
$start=5
from the URL using:

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


It is not returning anything.

Where removing
?query=post
, i.e,
blog/search/5
works fine. But I want to keep the query parameter and read the value.

Answer

That's because of the ? character in the URI. CodeIgniter URI parser (and any other standard URI parser) does not recognize what you have in mind. After the ? character, it's all query string, not URI segments. See the output of PHP's parse_url():

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

See? The first segment is blog, the second is search and the rest is the querystring.

You need to change your URI design in an standard way. For example:

blog/search/5?query=post

So that the call to $this->uri->segment(3) will return what you have in mind.

Speaking of CodeIgniter pagination library, see reuse_query_string and page_query_string configs in the documentation.

Comments