W3docs

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

In Symfony2, you can use the $this->get('kernel')->getRootDir() method inside a controller to get the server path to the web directory.

In Symfony2, you can use the $this->get('kernel')->getRootDir() method inside a controller to get the server path to the web directory. The method returns the path to the app/ directory. Since the web directory is located one level above app/, you can append ../web to the path to get the full path to the web directory. For example:

Example of using the $this->get('kernel')->getRootDir() method inside a controller to get the server path to the web directory in Symfony2

$webDirectory = $this->get('kernel')->getRootDir() . '/../web';
Info

Watch a video course: Learn object oriented PHP

Please note that getRootDir() was deprecated in Symfony 4.4 and removed in Symfony 5.0. For Symfony 3.4+, you can use $this->getParameter('kernel.project_dir') . '/../web', and for Symfony 4.3+, you can use $this->getParameter('kernel.public_dir') directly.