CodeIgniter really does not like query strings. It's just downright mean.
$this->uri->uri_string()removes the query string. Why?
current_url()from the url helper removes the query string. Why?
- You can use query strings instead of segment-based urls such as
http://example.com/controller_name/method_namebut they have a nasty warning:
If you are using query strings you will have to build your own URLs, rather than utilizing the URL helpers (and other helpers that generate URLs, like some of the form helpers) as these are designed to work with segment based URLs.
Not a good deal! Plus there are no built-in helpers or libraries to grab the query string and do stuff with it.
But why use query strings at all? I thought segments were better?
- Unlike URI segments, query string segments are all optional. If you have 5 key/value pairs, you can include just items 1 and 5 if you want.
- Unlike URI segments, query string segments can be put in any order. If you have the same 5 items you can order them like 4,5,3,1,2 if you want.
These are big deals, because they are a giant pain in the ass with segments. For instance, let's say you have 5 segments and you just want to change segment 5 from the default. You have to send the default values for segments 1-4 first! So your url ends up looking something like this:
Looking at that url it makes no sense. You don't know what 1, true, false, or 0 refer to. But you are forced to type them all. What happens if one of these default values change? Or if the order changes? Or if you have to add or remove a segment? You have to change all your URLs! What a pain in the ass!!
Now segment-based urls are fine for hierarchical websites such as
/products/outdoor/chainsaws/12. But for web applications, they totally suck. The way I see it there are two possible ways to fix this in CodeIgniter. You can either extend the URI and URL classes or write a new helper/library. I chose not to mess with URLs and just create a helper so I could use it in a view by just calling a function without
$this->helper_name-> in front. So here's my query_string_helper:
Query String Helper
It has just two functions:
query_string($add, $remove, $include_current)This just echoes the query string with no params.
- Param 1 allows you to add an array of items to the query string.
- Param 2 you can either send a string of a key you want to remove or send an array of keys you want to remove.
- Param 3 lets you ditch the current query string if you want and just make a new one.
uri_query_string( same params as above )This includes the full current uri with the query string on the end. It allows you to manipulate the query string in the same ways as above.
Now you can just replace all your
current_url() calls with
uri_query_string() and you're good to go!