CodeIgniter Q & A

 

How to set up custom routes in CodeIgniter?

Setting up custom routes in CodeIgniter is a powerful way to define how URLs are mapped to specific controller methods, allowing you to create user-friendly and customized URL structures for your web application. Here’s a step-by-step guide on how to set up custom routes in CodeIgniter:

  1. Route Configuration File: Custom routes are typically defined in the `application/config/routes.php` file. Open this file in your text editor or IDE to start configuring your custom routes.

 

  1. Basic Routing: To set up a basic custom route, you can use the following syntax:
```php

   $route['desired_url'] = 'controller/method';

   ```

   – `desired_url` is the URL you want to create. For example, if you want to map `example.com/about` to a `AboutController` and its `index()` method, you can use: `$route[‘about’] = ‘AboutController’;`.

 

  1. Route Parameters: You can also define routes with parameters, making your URLs dynamic. For instance, if you want to create URLs like `example.com/products/123`, where `123` is a product ID, you can use the following route:
  ```php

   $route['products/(:num)'] = 'ProductsController/show/$1';

   ```

   – `(:num)` is a placeholder for a numeric value, and `$1` represents the first captured value (the product ID) in the URL.

 

  1. Wildcard Routing: CodeIgniter allows you to use wildcard routing to capture multiple URL segments and pass them to a controller method. For example:
  ```php

   $route['category/(:any)/product/(:num)'] = 'ProductsController/showByCategory/$1/$2';

   ```

   – `(:any)` captures any string, and `$1` and `$2` represent the captured values in the URL.

 

  1. Regular Expressions: For more complex routing patterns, you can use regular expressions. For instance, to match URLs with a year and a month, you can use:
 ```php

   $route['(\d{4})/(\d{2})'] = 'CalendarController/show/$1/$2';

   ```

 

  1. Testing Routes: After defining custom routes, make sure to test them in your browser to ensure they work as expected. CodeIgniter will route the URLs according to your custom configurations.

 

By following these steps and utilizing the flexibility of CodeIgniter’s routing system, you can set up custom routes that align with your application’s requirements, making your URLs more user-friendly and improving the overall user experience. Custom routes are a powerful feature that allows you to create a clean and organized URL structure for your web application.

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Experienced Full Stack Systems Analyst, Proficient in CodeIgniter with extensive 5+ years experience. Strong in SQL, Git, Agile.