I'm new to Slim Framework. How to get the base URL like with the Codeigniter function base_url()
?
Thanks
You need to set the base url manually FIRST before you can get it as in this:
$app->hook('slim.before', function () use ($app) {
$app->view()->appendData(array('baseUrl' => '/base/url/here'));
});
<base href="{{ baseUrl }}" />
Jul 14, 2012 at 5:45
With Slim v3, as it implements PSR7, you can get a PSR7 Uri object and call the getBasePath() method that Slim3 adds on it. Simply write:
$basePath = $request->getUri()->getBasePath();
From Slim v3 documentation :
Base Path
If your Slim application's front-controller lives in a physical subdirectory beneath your document root directory, you can fetch the HTTP request's physical base path (relative to the document root) with the Uri object's getBasePath() method. This will be an empty string if the Slim application is installed in the document root's top-most directory.
Be aware that the getBasePath() method is added by the framework and is not part of PSR7 UriInterface.
getBasePath()
in the PSR-7 Uri interface.
Nov 23, 2017 at 18:04
getBasePath()
method is specific of Slim\Http\Uri
, it is not PSR-7 compliant. Given that the rest of the documentation suggests, and rightfully so, to hint against PSR-7 interfaces, using the implementation specific method will result in a vendor lock-in and will compromise the portability that PSR-7 support was meant to give in the first place. To clarify your answer, I would suggest to drop the PSR-7 reference, because as it is now it implies that the suggested method is part of the standard.
Nov 24, 2017 at 10:28
getBaseUrl()
Feb 22, 2019 at 2:08
In a recent app where we're using Twig, we assign the httpBasePath as follows:
$view = $app->view()->getEnvironment();
$view->addGlobal('httpBasePath', $app->request->getScriptName());
The addGlobal()
method is probably equivalent to $app->view()->appendData()
, I'm not sure.
The advantage of using $app->request->getScriptName()
is that we don't have to manually set a folder name or care what it is – one developer can have the repo located at http://example.localhost
and another can have it at http://localhost/projects/slim
and no configuration is required.
Try this in index.php to set the base url for the view
$app->hook('slim.before', function () use ($app) {
$posIndex = strpos( $_SERVER['PHP_SELF'], '/index.php');
$baseUrl = substr( $_SERVER['PHP_SELF'], 0, $posIndex);
$app->view()->appendData(array('baseUrl' => $baseUrl ));
});
I can get the base url with {{ app.request.getRootUri }}
(I'm using Twig template engine).
Incidentally, this is the same as the 'SCRIPT_NAME' environment variable.
if you are using TWIG then in Slim v3 call -
{{ base_url() }}
or use {{ path_for('yourRouteName') }}
The easiest way to get the base url is to append the request url and the request root url like below:
$req = $app->request;
$base_url = $req->getUrl()."".$req->getRootUri()."/";