I've seen several questions on StackOverflow that handle how to detect the user environment when a script is served via Apache and have such a system in place which works perfectly. The script depends on the Environment vars set by Apache.
Now I'm creating several tools that need to run in php CLI mode but I don't know how to detect the environment in CLI mode since the apache env vars aren't present there.
I'm thinking about reading the hostname of the server with gethostname() but don't know if that's the best solution and a reliable solution.
What is considered the best way to detect your environment when running in CLI mode with PHP
Clarification:
I'm not looking for a way to detect if i'm running a script from CLI, that base is covered. I'm looking for a way to determine what server my script is running on (DEV, STAGING or PRODUCTION) through CLI means, thus not reading the apache env variables set in my VHOST that are present when running the same script through a browser.
PHP's Command Line Interface (CLI) allows you to execute PHP scripts when logged in to your server through SSH. ServerPilot installs multiple versions of PHP on your server so there are multiple PHP executables available to run.
On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.
The best way to do this for PHP in Apache is by creating a separate Apache configuration file to will their values. Using Debian and Ubuntu as an example, the config file containing the environment variables should be stored in the /etc/apache2/conf-available directory.
You can use php_uname('n')
to get the hostname of your current machine. From there it's up to your implementation to determine whether it's production, staging, or development, either based on patterns in host name, hard-coded values, or some other configuration file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With