I’m doing a quick article on the subject even though it is probably known by most. Nevertheless, it happens to me while discussing with other developers that not everyone knows the auto_prepend_file system which can be a practical way to manage its constants.
Management of PHP constants according to the environment (DEV, PROD, recipe, etc.)
As we know, in many development projects (and PHP projects are no exception) you will have to manage a certain number of constants (path, urls, accounts, etc.). And these constants are generally different between development and production.
We can collect these constants in a configuration file inside a project, which can be a good way to do it, but how to manage the fact of taking the constants of development in development and those of production in prod without put a series of if?
Auto_prepend_file via php.ini
There is a fairly simple method, which can be effective in this case.
Constants must be centralized in a PHP file. This already has the merit of putting them all in the same place.
Next, we will use the “ auto_prepend_file ” property from the php.ini configuration file. This will have the effect of loading this file each time a PHP file is called, before the latter. Thus, we are sure to have all our constants before doing the desired PHP processing (like for an include).
In the php.ini, the syntax is as follows by changing the path to the file to put yours:
auto_prepend_file = /var/www/intranet/lib/config/prod_config.php
In the path above, you see in the file name that there is “prod”. You can create two files, a dev_config.php and a prod_config.php. It is then sufficient, depending on the server to be configured, to point to one or the other. As you know, there is a php.ini for the apache server, and one for the CLI. You can choose to use the same, or have a config file dedicated to the CLI, the operation is the same.
I recall on the other hand that this file is loaded with each call of a PHP. So, be careful not to have any errors in this file at the risk of having a certain number of logs