Repository navigation
Configuration
The third constructor argument is a configuration array. Every key is optional.
use InitPHP\Router\Router;
$router = new Router($request, $response, [
'paths' => [
'controller' => null, // Absolute path to the controller directory.
'middleware' => null, // Absolute path to the middleware directory.
],
'namespaces' => [
'controller' => null, // Namespace prefix for controller classes.
'middleware' => null, // Namespace prefix for middleware classes.
],
'base_path' => '/', // Sub-directory the app runs in.
'variable_method' => false, // Enable the POST `_method` override.
'trusted_proxies' => [], // Proxies whose X-Forwarded-For header is trusted.
'argument_new_instance' => false, // Inject fresh request/response instances.
// Optional integrations:
'container' => $psr11Container, // A PSR-11 ContainerInterface.
'cache' => [
'enable' => false,
'path' => null, // File for the compiled route table.
'ttl' => 86400, // Seconds.
],
]);Used to locate controller and middleware classes referenced by short name. See Controllers and Middleware.
If the app is served from a sub-directory (e.g. https://host/app/), set
base_path to '/app' so route paths match relative to it. The default '/'
means the app runs at the domain root.
When true, the HTTP method can be overridden with a _method request
parameter — useful for HTML forms, which can only send GET/POST:
$router = new Router($request, $response, ['variable_method' => true]);
$router->put('/articles/{id}', 'ArticleController@update');<form method="post" action="/articles/42">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">
</form>The override is only honoured when the real request method is POST and the
value is one of the supported methods. It is read from the POST parameters only:
the parsed body of a PSR-7 server request when it is an array, otherwise
$_POST. A _method in the query string, or on a GET request, is ignored.
Check the token before the handler changes anything, in the handler or in a middleware (the session must be started and hold the token you rendered into the form):
function assertValidCsrfToken(): void
{
$expected = (string) ($_SESSION['csrf_token'] ?? '');
$sent = (string) ($_POST['csrf_token'] ?? ''); // request body only, never the query string
if ($expected === '' || !hash_equals($expected, $sent)) {
http_response_code(403);
exit('Invalid CSRF token.');
}
}Changed after 3.0.0: the override no longer applies to
GETrequests. Releases up to 3.0.0 read_methodfrom$_REQUEST(query string and body) and did not require a realPOST, so a link such ashttps://example.com/articles/42?_method=DELETEwas routed asDELETE. Now a request that is not aPOST, and a_methodthat is not in the POST body, is routed under its real method. A client that relied onGET ...?_method=PUTmust send aPOSTwith the field in the body.The override is still not a substitute for a CSRF token: a cross-site HTML form can submit a
POSTwith_method=DELETEin its body, so keep the token check above on every state-changing route. A PSR-7 server request whose parsed body comes from a JSON payload ({"_method": "DELETE"}) is read the same way. With a PSR-7 server request only its parsed body counts, never$_POST.Leave
variable_methodoff (the default) for JSON APIs and any app that does not submit HTML forms.
A list of IP addresses and CIDR ranges (IPv4 or IPv6) of the reverse proxies and
load balancers in front of the application. It decides where the client address
used by ip() groups comes from:
$router = new Router($request, $response, [
'trusted_proxies' => ['192.0.2.5', '10.0.5.0/28'], // your proxies only, never a whole internal network
]);- By default the list is empty: the client address is
REMOTE_ADDR, the address of the TCP peer, and theX-Forwarded-Forheader is ignored. TheClient-IPheader is never read. - When
REMOTE_ADDRis one of the listed proxies,X-Forwarded-Foris read from right to left. Each trusted proxy is skipped, and the first address that is not trusted is the client. If every entry is trusted, the leftmost one is used. As long as the client's own address is not in the list, entries it added to the left of what your proxy appended are never reached. A client whose address is inside a listed range (an internal host in10.0.0.0/8, say) is skipped like a proxy, and the value it wrote to the left is read instead, so list your proxies' addresses, not whole internal networks. - An entry that is not a valid IP address (
unknown, a value with a port such as203.0.113.7:4711, an empty item) breaks the chain: no client address is reported (it isnull), so noip()group matches. Configure the proxy to send bare addresses. - IPv4-mapped IPv6 addresses (
::ffff:192.0.2.10) are treated as the IPv4 address inREMOTE_ADDR, in the header, intrusted_proxiesand in theip()allow-list. Addresses are compared in canonical form, so2001:DB8::5in anip()list matches a client2001:db8::5. - An option that is not an array, or an entry that is not an IP address or CIDR
range, makes the constructor throw
InvalidArgumentException, so a typo does not silently trust nothing, or everything. - With a PSR-7 server request,
REMOTE_ADDRis taken fromgetServerParams()when it returns any, otherwise from$_SERVER; a bag withoutREMOTE_ADDRyields no client address (null), so noip()group matches. TheX-Forwarded-Forheader is read from the request itself (getHeader(), several header lines are joined in order), because the server parameters of some runtimes (ReactPHP) carry noHTTP_*entries;HTTP_X_FORWARDED_FORis only the fallback when the request has no such header. A plain request has no server parameters, so$_SERVERis used.
List only proxies you operate. A range wider than your real proxies (for example
0.0.0.0/0, or a whole internal network) lets a client forge the address again.
Upgrading with a proxy on the same machine or network. If the proxy's own address is in an
ip()list (for exampleip('127.0.0.1', ...)behind a local nginx), do not upgrade without settingtrusted_proxies: every visitor then appears to come from the proxy, and the group opens to everyone.
By default, a handler parameter type-hinted with your request/response class
receives the shared instance. Set this to true to inject a newly
constructed instance instead. See Dependency Injection.
A PSR-11 ContainerInterface. When set,
controllers and class-typed handler dependencies are resolved through it. See
Dependency Injection.
Caches the compiled route table to a file. See Caching.
Next: Routing.
initphp/router · MIT License · part of the InitPHP family
Source · Issues · Discussions · Packagist · Contributing · Security Policy
Getting Started
Defining Routes
Handling Requests
- Dependency Injection
- Middleware
- Static File Links
- Error Handling
- Caching
- Health Checks
- Readiness Linter
Reference
Migration