By default, Symfony reads environment variables from a .env file located in the project root. However, when using the Runtime component, the path to this file can be changed. In some cases, you may want to know which .env file Symfony is currently loading. This can be helpful for debugging environment issues, logging, or writing a custom configuration reader.
Symfony exposes the current .env file path through the SYMFONY_DOTENV_PATH environment variable. The Autowire attribute can be used to inject this variable into the constructor property.
src/Controller/TestController.php
<?php
namespace App\Controller;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class TestController
{
public function __construct(
#[Autowire(env: 'SYMFONY_DOTENV_PATH')] private string $envPath,
) {
}
#[Route('/')]
public function index(): Response
{
return new Response($this->envPath); // /var/www/my_project/.env
}
}
Leave a Comment
Cancel reply