Skip to content

Core\Request\Mount::prefix

$mount->prefix(): string

Returns the part of the path that the server removed before your program started, such as /shop.

The server's configuration says which program answers which prefix. When a request for /shop/cart arrives at a program mounted at /shop, the server removes /shop, and Core\Request::path() returns /cart. prefix() returns /shop. Put it in front of every link and cookie path you write, so the same program works under any prefix.

The prefix starts with / and does not end with one. A program mounted at / has nothing removed, and prefix() returns "". The prefix is not tainted, because the person who runs the server wrote it, not the client.

The examples below read the prefix beside the path, read a prefix that a pattern matched, and limit a cookie to this program.

Return value

Returns string. The prefix, with a slash at the start and none at the end. The result is "" when the mount removes nothing. It is not tainted, because the server configuration sets every mount when the server starts. The prefix is the operator's text, and the client did not choose it.

Examples

The prefix and the path

<?nvs
// Shows how the prefix and the path together make the address that the client asked for.
// The server serves this program at `/shop`. The client asked for `/shop/cart`.
string $prefix = Core\Request::mount()->prefix();
// This prints "prefix: /shop".
echo 'prefix: ', $prefix, "\n";
// `path()` returns the address without the prefix. This prints "path: /cart".
echo 'path: ', Core\Request::path(), "\n";
// The two together are the full address. This prints "address: /shop/cart".
echo 'address: ', $prefix, Core\Request::path(), "\n";
Output
prefix: /shop
path: /cart
address: /shop/cart

A prefix from a pattern

<?nvs
// Shows what `prefix()` returns when a pattern chose the mount.
// The server has one folder for each customer, and the pattern `/{1:lower}`
// serves the folder `Acme` at `/acme`. The client asked for `/acme/orders`.
Core\Request\Mount $mount = Core\Request::mount();
// `prefix()` returns the whole prefix, in lower case. This prints "prefix: /acme".
echo 'prefix: ', $mount->prefix(), "\n";
// `captures()` returns the folder name. This prints "customer: Acme".
echo 'customer: ', $mount->captures()[0], "\n";
Output
prefix: /acme
customer: Acme

A cookie for this program only

<?nvs
// Shows how a program limits its cookie to the addresses under its own prefix.
// The server serves this program at `/shop`, and another program at `/blog`.
// A cookie with the path `/shop` goes only to this program.
string $prefix = Core\Request::mount()->prefix();
// A program at `/` has the prefix "", and its cookie path is "/".
string $cookiePath = $prefix == '' ? '/' : $prefix;
// This prints "Set-Cookie: cart=3; Path=/shop".
echo 'Set-Cookie: cart=3; Path=', $cookiePath, "\n";
Output
Set-Cookie: cart=3; Path=/shop