Search code examples
phpcodeigniterurisegmenturl-mapping

CodeIgniter URL Function Segment as Query String


Is there a way without changing the whole configuration of CodeIgniter to get the URI segment for function ($this->uri->segment(2)) as a regular query string instead of being directly mapped to a function?

For example, I would be forced to have a URL like this:

http://localhost/books/functionName/bookNumber

I would like to have the bookNumber number right after the controller name (books):

http://localhost/books/bookNumber If I have the URL like this it would map the bookNumber to a function name.


Solution

  • You could use CodeIgniter's URI Routing to achieve your desired URL format.

    If you add the following route to application/config/routes.php, then any URL that is entered that matches the route on the left, will map to the controller/function on the right:

    $route['books/(:num)'] = "books/functionName/$1";
    

    This will map a URL such as http://localhost/books/123, to the functionName function, in the books controller, passing 123 as the parameter.

    This assumes that your 'book numbers' are always numbers (it would not work for strings), as (:num) will match segments only containing numbers.