仅从Cron运行php脚本或检查cron是否发出请求? [英] Run a php script only from Cron or check if request from cron?

查看:93
本文介绍了仅从Cron运行php脚本或检查cron是否发出请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅从cron运行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

我正在尝试使用参数调用php文件。但是它们都不起作用:

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'

我不能使用$ _GET,$ _ SESSION或$ argv。我如何用参数调用文件?

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

推荐答案

如果您要这样做,是因为您需要检查脚本是否为不是从网络请求中调用,则可以使用 php_sapi_name 函数以查看调用方法-如果它是一项cron作业,则该函数应返回 cli 表示命令行调用。但是,它不能帮助区分cron作业和常规命令行调用。

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.

如果您还需要区分cron作业和命令行调用脚本后,您可以检查运行脚本的用户,并查看运行cron作业的用户是否相同。例如,可以在* nix系统上使用 posix_getuid posix_getlogin 函数。

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.

最后,如果您担心有人以cron作业所有者的身份登录并从命令行运行脚本,则应该对cron作业使用没有外壳的单独用户。

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.

这篇关于仅从Cron运行php脚本或检查cron是否发出请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆