Ensure a PHP script is only ever run as a cron job?-ThrowExceptions

Exception or error:

How can I ensure a user can not run a PHP script and that it is only ever run as part of a cron job?

How to solve:

You can set an environment variable in your crontab. A line like IS_CRON=1 can be placed at the beginning of your crontab, then check in your php program for get_env("IS_CRON") == 1.

Of course, you should also use file permissions as they’re not so easily bypassed. If this is run as part of root’s cron, chown root:root yourscript.php and chown 700 yourscript.php.

As ircmaxell says, it’d be better to run as a user other than root assuming you don’t need root permissions for what you’re doing. I was just taking a guess about your setup.


How about having your PHP script check if $_SERVER['REMOTE_ADDR'] is empty, and if it is not, then have the script exit without doing anything further.


There are probably a number of ways to do this. Off the top of my head, I would say that placing it in a directory owned by root, and only readable by root might get close to achieving the effect you are looking for.

Are there any processes you are looking specifically to restrict it from? If so, using permissions, make it not readable to any of those processes.


I would suggest setting an environment variable within your crontab and then checking for this within your PHP script


Create a user for cron jobs, and set permissions of the script so it can only be run as this user. Of course you then need to put the script in that user’s crontab, which you can do by logging in as that user and running crontab. Just don’t give that user’s password to just any other user…

At first I was also thinking of setting an environment variable which would prevent running this script from the web… But just not putting the script in the space where the web server looks for pages for websites, would do the same.

And nothing is stopping a random user from first setting the environment variable and then running the script.

Leave a Reply

Your email address will not be published. Required fields are marked *