简体   繁体   中英

Run a php script only from Cron or check if request from 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?

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.

You could just pass a parameter to your script that says it was called in a cron job. Take a look at the question: cron-jobs-calling-a-php-script-with-variables

How about passing some auth key to your script which is only stored in the cron_script and the receiver script. On call check if the authkey is transmitted via $_GET['auth_key'] in your receiver script.

Like: http://www.example.com/receiver_script.php?auth_key= "WhatEverYouWant"

Allright, I found the solution. If you want to call the php file with a GET parameter you should call file this way:

php -q /home/domain/public_html/cronjob.php name=value

and you can get this data in php file using $_GET:

$_GET['name']

or argv:

$argv[1]

If you want to pass a parameter to just argb :

php -q /home/domain/public_html/cronjob.php value

Other examples that I found in the websites don't work but these work great..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM