Can PHP detect if its run from a cron job or from the command line?
Instead of detecting when the script is run from the crontab, it's probably easier to detect when you're running it manually.
There are a lot of environment variables (in the $_ENV array) that are set when you run a script from the command line. What these are will vary depending on your sever setup and how you log in. In my environment, the following environment variables are set when running a script manually that aren't present when running from cron:
- TERM
- SSH_CLIENT
- SSH_TTY
- SSH_CONNECTION
There are others too. So for example if you always use SSH to access the box, then the following line would detect if the script is running from cron:
$cron = !isset($_ENV['SSH_CLIENT']);