[php] How to get the server path to the web directory in Symfony2 from inside the controller?

You also can get it from any ContainerAware (f.i. Controller) class from the request service:

  • If you are using apache as a webserver (I suppose for other webservers the solution would be similar) and are using virtualhosting (your urls look like this - localhost/app.php then you can use:

    $container->get('request')->server->get('DOCUMENT_ROOT');
    // in controller:
    $this->getRequest()->server->get('DOCUMENT_ROOT');
    
  • Else (your urls look like this - localhost/path/to/Symfony/web/app.php:

    $container->get('request')->getBasePath();
    // in controller:
    $this->getRequest()->getBasePath();