I'm looking for way to PHP to detect if a script was run from a manual invocation on a shell (me logging in and running it), or if it was run from the crontab entry.
I have various maintenance type scripts written in php that i have set to run in my crontab. Occasionally, and I need to run them manually ahead of schedule or if something failed/broken, i need to run them a couple times.
The problem with this is that I also have some external notifications set into the tasks (posting to twitter, sending an email, etc) that I DONT want to happen everytime I run the script manually.
I'm using php5 (if it matters), its a fairly standard linux server environment.
Any ideas?
To check to see if the cron daemon is running, search the running processes with the ps command. The cron daemon's command will show up in the output as crond. The entry in this output for grep crond can be ignored but the other entry for crond can be seen running as root. This shows that the cron daemon is running.
You can find them in /var/spool/cron/crontabs. The tables contain the cron jobs for all users, except the root user. The root user can use the crontab for the whole system. In RedHat-based systems, this file is located at /etc/cron.
Once the PHP script is called for the first time by the crontab daemon, it can execute tasks in a time period that matches the logic of your application without keeping the user waiting. In this guide, you will create a sample cron_jobs database on an Ubuntu 20.04 server.
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:
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']);
if (php_sapi_name() == 'cli') { if (isset($_SERVER['TERM'])) { echo "The script was run from a manual invocation on a shell"; } else { echo "The script was run from the crontab entry"; } } else { echo "The script was run from a webserver, or something else"; }
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