CodeIgniter 4 – URLs

CodeIgniter 4 provides a flexible and secure way to manage URLs and handle user input through the URI. This guide will cover the concepts and steps to manage the URL structure, handle subfolders, ensure URI security, and remove index.php from your URLs.

1. URL Structure in CodeIgniter 4

In CodeIgniter 4, URLs map directly to the controller and its method.

URL Format

http://your-domain.com/controller/method/parameter
  • Controller: The class name of your controller.
  • Method: The method of the controller you wish to invoke.
  • Parameter: Optional data passed to the method.

Example

For a controller Product with a method details($id):

class Product extends BaseController
{
    public function details($id)
    {
        echo "Product ID: " . $id;
    }
}

The URL:

http://your-domain.com/product/details/42

Would output:

Product ID: 42

2. Setting Base URL with Subfolders

If your application is in a subfolder, update the baseURL in the app/Config/App.php file.

Steps:

  1. Locate app/Config/App.php.
  2. Find the baseURL property.
  3. Update it to include the subfolder.

Example:

If your application is located at http://your-domain.com/myapp/, set:

public $baseURL = 'http://your-domain.com/myapp/';

This ensures that all generated URLs (e.g., with site_url() or base_url()) include the correct base path.

3. URI Security in CodeIgniter 4

CodeIgniter 4 ensures secure handling of URIs by default:

  • Disallows direct access to certain directories (app, system).
  • Escapes special characters in URIs.
  • Validates input data for malicious content.

Sanitizing Input from URIs

CodeIgniter uses a filter system to validate or sanitize URI data:

// Retrieve sanitized GET input
$name = $this->request->getGet('name', FILTER_SANITIZE_STRING);

// Retrieve validated URI segments
$segment = $this->request->getUri()->getSegment(1);

Using Route Constraints

To ensure URI parameters meet specific criteria, you can use route constraints.
Example:

$routes->add('product/(:num)', 'Product::details/$1'); // Only allow numbers

This will ensure (:num) accepts only numeric values.

4. Removing index.php from URLs

By default, CodeIgniter 4 includes index.php in URLs. To make URLs cleaner, you can remove it.

Steps to Remove index.php

Step 1: Enable .htaccess

  1. Ensure the .htaccess file is present in the public/ directory.
  2. The default .htaccess file already includes rules to remove index.php.

Default .htaccess:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /myapp/ # Change this if your app is in a subfolder
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Step 2: Move Your Application

Ensure your application files are structured correctly:

  • public/ folder should be the webroot (accessible via the browser).
  • Other folders like app/ and system/ should remain outside the webroot.

Example:

/myapp
    /app
    /system
    /writable
    /public (webroot)

Step 3: Update Your Web Server Configuration

  • For Apache:

1. Ensure mod_rewrite is enabled:

sudo a2enmod rewrite
sudo systemctl restart apache2

2. Update the virtual host configuration to point to the public/ folder:

<VirtualHost *:80>
    ServerName your-domain.com
    DocumentRoot /path/to/myapp/public
    <Directory /path/to/myapp/public>
        AllowOverride All
    </Directory>
</VirtualHost>
  • For Nginx: Update the server block to set the root to public/ and handle index.php:
server {
    server_name your-domain.com;
    root /path/to/myapp/public;

    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

Step 4: Test Your Application

Visit a route, such as:

http://your-domain.com/product/details/42

If properly configured, the index.php part should no longer appear.

5. Practical Example of a Full Setup

Directory Structure:

/myapp
    /app
    /system
    /writable
    /public
        index.php
        .htaccess

Routes Configuration (app/Config/Routes.php):

$routes->get('/', 'Home::index');
$routes->get('product/(:num)', 'Product::details/$1');

Controller (app/Controllers/Product.php):

namespace App\Controllers;

class Product extends BaseController
{
    public function details($id)
    {
        echo "Product ID: $id";
    }
}

Summary

  1. URL Structure: CodeIgniter maps URLs to controller methods (controller/method/parameter).
  2. Base URL: Configure baseURL in App.php to account for subfolders.
  3. URI Security: Use filtering and route constraints to sanitize and validate user input.
  4. Removing index.php: Use .htaccess (Apache) or try_files (Nginx) to remove index.php.

This setup results in cleaner, more professional URLs and ensures security and scalability in your CodeIgniter 4 application.

Share the Post:

Related Posts