> For the complete documentation index, see [llms.txt](https://docs.cmsfullform.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.cmsfullform.com/documents/middleware.md).

# Middleware

Middleware in PHP-Fast allows you to filter HTTP requests entering your application. This can be useful for tasks such as user authentication, input validation, and permission checks before the request reaches the controller.

## Create Middleware

All middleware classes should be placed in the `application/Middleware` directory. A middleware class contains a `handle()` method, which will be executed when the middleware is applied to a route or controller.

To ensure only authenticated users can access certain routes, let's create a simple authentication middleware.

**Steps to Create** `AuthMiddleware`

1. Navigate to `application/Middleware/`.
2. Create a new file named `AuthMiddleware.php`.
3. Add the following code to handle authentication:

```php
<?php

namespace App\Middleware;

class AuthMiddleware
{
    public function handle($request, $next)
    {
        // Check if the user is logged in
        if (!isset($_SESSION['user'])) {
            echo "Unauthorized access!";
            exit;
        }

        // Proceed to the next middleware or controller
        return $next($request);
    }
}
```

## Using Middleware in Route

To apply middleware to a route, include the middleware class name as an array in the route definition inside `application/Routes/web.php` or `application/Routes/api.php`.

Example: Adding `AuthMiddleware` to a Route in `web.php`

```php
$routes->get('admin', 'AdminController::index', [\App\Middleware\AuthMiddleware::class]);
```

## More Example

As the same `AuthMiddleware`, you can create a `PermissionMiddleware` to manage access control for different parts of your application.

1. Create a new file in `application/Middleware/` named `PermissionMiddleware.php`.
2. Add the following code to handle authentication:

```php
<?php

namespace App\Middleware;

class PermissionMiddleware
{
    public function handle($request, $next, $permissions = [])
    {
        // Retrieve the user's permissions from the session
        $userPermissions = $_SESSION['user_permissions'] ?? [];

        // Check if the user has the required permissions
        foreach ($permissions as $permission) {
            if (!in_array($permission, $userPermissions)) {
                echo "You have no permission to access this page!";
                exit;
            }
        }

        // Proceed to the next middleware or controller
        return $next($request);
    }
}
```

3. Add middleware to a route and pass the necessary permissions:

```php
$routes->get('admin/settings', 'AdminController::settings', [
    [\App\Middleware\PermissionMiddleware::class, ['manage_settings']]
]);
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.cmsfullform.com/documents/middleware.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
