I have a number of batch processes that run using PHP as the command interpreter, and discovered after making a change to one of them the other day that the variables available to PHP in the $_SERVER superglobal are different depending on whether it’s run via an SSH session or cron. This post shows the difference on Debian 6. The values available are probably the same on other distros.
$_SERVER using the CLI via SSH
Using the PHP command line interpeter (CLI) the following was displayed when running print_r($_SERVER), showing which variables are available:
Array ( [TERM] => xterm-color [SHELL] => /bin/bash [SSH_CLIENT] => A.B.C.D 58867 22 [SSH_TTY] => /dev/pts/0 [USER] => chris [MAIL] => /var/mail/chris [PATH] => /usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games [PWD] => /tmp [LANG] => en_NZ.UTF-8 [SHLVL] => 1 [HOME] => /home/chris [LOGNAME] => chris [SSH_CONNECTION] => A.B.C.D 58867 A.B.C.D 22 [_] => /usr/bin/php [OLDPWD] => /home/chris [PHP_SELF] => 1.php [SCRIPT_NAME] => 1.php [SCRIPT_FILENAME] => 1.php [PATH_TRANSLATED] => 1.php [DOCUMENT_ROOT] => [REQUEST_TIME] => 1327976915 [argv] => Array (  => 1.php ) [argc] => 1 )
Note that I’ve substituted the actual IP addresses with A.B.C.D in the example above.
$_SERVER using the CLI via cron
Running a PHP script under cron yields less variables in the $_SERVER array. My example script doing print_r($_SERVER) output this:
Array ( [HOME] => /home/chris [LOGNAME] => chris [PATH] => /usr/bin:/bin [LANG] => en_NZ.UTF-8 [SHELL] => /bin/sh [PWD] => /home/chris [PHP_SELF] => /tmp/1.php [SCRIPT_NAME] => /tmp/1.php [SCRIPT_FILENAME] => /tmp/1.php [PATH_TRANSLATED] => /tmp/1.php [DOCUMENT_ROOT] => [REQUEST_TIME] => 1327976941 [argv] => Array (  => /tmp/1.php ) [argc] => 1 )
Reason for posting this
As I mentioned at the start of this post, I run a lot of batch processes via cron using PHP. Sometimes I need to use $_SERVER variables and as I discovered they’re not all available under cron, so testing via the command line won’t necessarily yield the same response as when using cron.
I’ve posted this as a quick reference should I need to use $_SERVER variables in the future using cron so I can see what’s available. With the issue I was having the other day, it was the [USER] variable being present from the command line using SSH which isn’t present when using cron.