> 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
