Original URL Slim Framework

I am new to Slim Framework. How to get the base URL, for example, using the Codeigniter base_url() function?

thanks

+6
source share
7 answers

You need to set the base url manually FIRST before you can get it like this:

 $app->hook('slim.before', function () use ($app) { $app->view()->appendData(array('baseUrl' => '/base/url/here')); }); 

http://help.slimframework.com/discussions/questions/49-how-to-deal-with-base-path-and-different-routes

+17
source

With Slim v3, since it implements PSR7, you can get the PSR7 Uri object and call the getBasePath () method, which Slim3 adds to it. Just write:

 $basePath = $request->getUri()->getBasePath(); 

From slim v3 Documentation :

Base path

If your external Slim application controller is located in a physical subdirectory under the root directory of your document, you can get the physical base path of the HTTP request (relative to the document root) using the getBasePath () method of the Uri object. This will be an empty line if Slim is installed in the root directory of the root directory.

Remember that the getBasePath () method is added by the framework and is not part of the PSR7 UriInterface .

+11
source

In a recent application where we use Twig, we assign 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 need to manually set the folder name or care what it is: one developer can have a repo located at http://example.localhost , and the other may be http://localhost/projects/slim and no configuration is required.

+6
source

Try setting the base url for the view in index.php

 $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 )); }); 
+4
source

I can get the base url with {{ app.request.getRootUri }} (I use the Twig template engine). By the way, this is the same as the SCRIPT_NAME environment variable.

+2
source

if you use TWIG and then in Slim v3 call -

 {{ base_url() }} 

or use {{ path_for('yourRouteName') }}

+2
source

The easiest way to get the base url is to add the request URL and the root URL of the request, as shown below: $req = $app->request; $base_url = $req->getUrl()."".$req->getRootUri()."/"; $req = $app->request; $base_url = $req->getUrl()."".$req->getRootUri()."/";

+1
source

Source: https://habr.com/ru/post/920474/


All Articles