Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a php script only from Cron or check if request from cron?

Tags:

security

php

cron

How can I run a php script only from cron or is it possible to check if the request comes from cron?

EDİT

I am trying to call php file with a parameter. But none of them work:

php -q /home/domain/public_html/cronjob.php?i=a
php -q /home/domain/public_html/cronjob.php par1
php -q /home/domain/public_html/cronjob.php par1=a
php -q /home/domain/public_html/cronjob.php par1='a'

I can't use $_GET,$_SESSION or $argv. How I call the file with a parameter?

like image 922
Orçun yumarcı Avatar asked Oct 18 '25 19:10

Orçun yumarcı


1 Answers

If you're asking this because you need to check if the script is not called from a web request, you can use the php_sapi_name function to see the method of invocation - if it's a cron job, the function should return cli that indicates a command-line call. It does not, however, help distinguish between a cron job and a regular command-line call.

If you also need to distinguish between a cron job and a command-line invocation of the script, you can check the user running the script and seeing if it's the same that should be running the cron job. That could be done, for example, on a *nix system, with posix_getuid or posix_getlogin function.

Lastly, if you're worried someone's logging in as the cron job owner and running the script from command line, you should use a separate user with no shell for the cron jobs.

like image 142
pilsetnieks Avatar answered Oct 21 '25 10:10

pilsetnieks