Relative paths in PHP INI

I’ve always preferred to use relative file paths in my PHP INI, but ran into problems when running PHP from different directories. For example, a directive like error_log = "../logs/php_errors.log" will resolve to different paths when invoked by /public/index.php (e.g. Zend Framework) and /cli-config.php (e.g. Doctrine CLI). Some INI directives can be set at runtime by our application (see PHP_INI_ALL), but many cannot. I finally found the solution with environment variables.

In a past post, “Hosting PHP on IIS7”, I detailed my typical server configuration for PHP sites. For maximum flexibility, every site has its own PHP INI. To point PHP to its INI file, I create a FastCGI environment variable named PHPRC. The PHPRC variable stores the absolute path of the directory containing php.ini. So the PHPRC variable contains a path like C:\inetpub\wwwroot\Blog\public.

Now I can simply use the PHPRC environment variable in my PHP INI. For example:

  • error_log = "${PHPRC}/../logs/php_errors.log"
  • upload_tmp_dir = "${PHPRC}/../temp/uploads"
  • session.save_path = "${PHPRC}/../temp/sessions"

These paths will automatically update depending on which server runs my code. Granted, these paths are not truly relative. But as long as every server contains an absolute path to the PHP INI, I may as well reuse it.

Leave a Reply

Your email address will not be published.