Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 383
Starlin Avatar asked Oct 29 '10 17:10

Starlin


People also ask

Can a PHP script run forever?

You can make it run forever by either setting the value or call set_time_limit in your script (http://php.net/manual/en/function.set-time-limit.php).

Do Cronjobs run automatically?

The cron reads the crontab (cron tables) for running predefined scripts. By using a specific syntax, you can configure a cron job to schedule scripts or other commands to run automatically.


2 Answers

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.

like image 91
Brad Mace Avatar answered Sep 27 '22 17:09

Brad Mace


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.

like image 44
Grayson Avatar answered Sep 27 '22 15:09

Grayson