This page looks best with JavaScript enabled

Debugging PHP/Symfony3.4 code in production

 ·  🎃 kr0m

Many times we are not able to debug our PHP code easily, other times there is no trace of the error that is occurring neither in the web server logs nor in the application logs. In these cases, we can access the symfony dev environment where more debug information will be shown to us.

Let’s start by explaining how environments work in Symfony, by default we have 3 environments:

  • dev: Development, errors are more detailed with information for debugging.
  • prod: Production, caches are enabled and debug information is removed from errors.
  • test: Test, it is used to run functional tests that are not directly accessible via web browser.

Depending on the environment that is running, a configuration file will be loaded:

  • dev: config_dev.yml
  • prod: config_prod.yml
  • test: config_test.yml

NOTE: All environments have a common configuration, the config.yml file.

To run one environment or another, we just need to access app.php(prod) or app_dev.php(dev), by default symfony creates a .htaccess in the document root with:

cat web/.htaccess

DirectoryIndex app.php

This way, by default, the production environment will be served, but development will still be accessible. To protect it, we will restrict access to the loopback address:

vi web/app_dev.php

if (!in_array(@$_SERVERREMOTE_ADDR, array('127.0.0.1', '::1'))) {
 die('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

NOTE: If we start the integrated server, it will always load the dev environment by default, in this link we can read it in the official symfony documentation:

If you're using the built-in PHP web server, it knows to use the app_dev.php file.

To check which environment is running, we can use Monolog as explained in this article .

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$logger = new Logger('debugLogger');
$logDir = $this->container->get('kernel')->getLogDir();
$logger->pushHandler(new StreamHandler($logDir.'/debugLog.log', Logger::NOTICE));
$logger->notice('debugLogger ENV is now ready');

$runningEnvironment=$this->container->get('kernel')->getEnvironment();

To access dev, we must do it through an ssh tunnel:

ssh -L 8000:127.0.0.1:80 -A -g IP_SERVER

Then, we just need to access via HTTP through the tunnel:
http://localhost:8000/app_dev.php

If you liked the article, you can treat me to a RedBull here