CodeIgniter Routing Guide | Generated by AI

Home 2025.10

Overview of CodeIgniter Routing

CodeIgniter’s routing system allows you to map URLs (URIs) to specific controller classes and methods, overriding the default URL pattern of example.com/controller/method/id/. This is useful for creating SEO-friendly URLs, handling RESTful APIs, or simply customizing how requests are processed.

The provided code snippet is from CodeIgniter’s routes.php configuration file. It defines an associative array $route where each key is a URI pattern, and the value is either a string (controller/method) or an array specifying different behaviors by HTTP method (e.g., GET, POST). This setup supports both standard routing and method-specific routing.

I’ll break down how routes are defined, how they work, and how to use them, based on CodeIgniter’s standard behavior and the example in your code. For full details, refer to the official CodeIgniter User Guide on routing: https://codeigniter.com/userguide4/general/routing.html.

1. How to Define Routes

Routes are defined in application/config/routes.php as an array. You add entries to $route[]. Here’s the syntax:

Tips for Defining Routes in Your Code:

2. How Routes Work

CodeIgniter’s router processes each incoming request in this order:

  1. Parse the URI: Breaks down the URL into segments (e.g., /users/123/edit → segments: users, 123, edit).
  2. Match Against Routes: Checks the $route array from top to bottom. It looks for exact matches first, then patterns with wildcards.
    • If a match is found, it maps to the specified controller/method, passing dynamic parts (e.g., 123) as method arguments.
    • If no match, it falls back to the default pattern (Controller::method/id/).
  3. Load Controller & Method: CodeIgniter instantiates the controller, calls the method, and passes any URI segments or captured groups.
  4. Method-Specific Handling: If the route is an array (like in your code), it checks the HTTP method (GET, POST, etc.) from the request.
  5. Fallback: Unmatched requests trigger a 404, or the $route['404_override'] if set.

Example Flow:

Key Mechanics:

3. How to Use Routes

Using routes means setting them up as above, then leveraging them in your application (controllers, views, etc.).

If you have specific questions about a route in your file (e.g., why (\d+) is used or how to add a new one), provide more details! For CodeIgniter setup, ensure CI_VERSION is defined in your index.php.


Back

x-ai/grok-code-fast-1

Donate