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'));
});
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.
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()."/";