Slim 4 get base url

Hi.
In slim 3 there was a method to get the base url from the uri.
What is the right way to get the same with slim 4 ?
Thanks.

The Slim 4 App class has a App::getBasePath() method

Example:

$basePath = $app->getBasePath();

But that doesn’t return the base application url. It returns the base path that is empty by default if you don’t set it.

Yes, getBasePath only returns the value you set with setBasePath($basePath). By defaults it’s empty.

Then what exactly do you mean by base application url?
Do you have a Slim 3 example?

I mean this method in slim 3 https://github.com/slimphp/Slim/blob/200c6143f15baa477601879b64ab2326847aac0b/Slim/Http/Uri.php#L825.

I see. It looks like the App::getBaseUrl method has been removed in Slim 4 (because it’s not part of PSR-7).

As replacement you could use or implement a Middleware to detect the baseUrl.

Example

<?php

namespace App\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
 * Middleware.
 */
final class BaseUrlMiddleware implements MiddlewareInterface
{
    /**
     * The app base path.
     *
     * @var string
     */
    private $basePath;

    /**
     * The constructor.
     *
     * @param string $basePath The slim app basePath ($app->getBasePath())
     */
    public function __construct(string $basePath = '')
    {
        $this->basePath = $basePath;
    }

    /**
     * Invoke middleware.
     *
     * @param ServerRequestInterface $request The request
     * @param RequestHandlerInterface $handler The handler
     *
     * @return ResponseInterface The response
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $request = $request->withAttribute('base_url', $this->getBaseUrl($request));

        return $handler->handle($request);
    }

    /**
     * Return the fully qualified base URL.
     *
     * Note that this method never includes a trailing /
     *
     * @param ServerRequestInterface $request The request
     *
     * @return string The base url
     */
    public function getBaseUrl(ServerRequestInterface $request): string
    {
        $uri = $request->getUri();
        $scheme = $uri->getScheme();
        $authority = $uri->getAuthority();
        $basePath = $this->basePath;

        if ($authority !== '' && strpos($basePath, '/') !== 0) {
            $basePath .= '/' . $basePath;
        }

        return ($scheme !== '' ? $scheme . ':' : '')
            . ($authority ? '//' . $authority : '')
            . rtrim($basePath, '/');
    }
}

Setup

$app = AppFactory::create();

// optional
// $app->setBasePath($basePath);

// Register middleware
$app->addMiddleware(new BaseUrlMiddleware($app->getBasePath()));

// ...

$app->run();

Usage

$baseUrl = (string)$request->getAttribute('base_url'); // https://example.com

Source

1 Like