简体   繁体   English

确保PHP脚本只作为cron作业运行?

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

如何确保用户无法运行PHP脚本,并且只能作为cron作业的一部分运行?

You can set an environment variable in your crontab. 您可以在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 . IS_CRON=1这样的行可以放在你的crontab的开头,然后在你的php程序中检查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 . 如果这是作为root的cron的一部分运行的,则chown root:root yourscript.phpchown 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. 正如ircmaxell所说,假设你不需要root权限来做你正在做的事情,那么以root用户身份运行会更好。 I was just taking a guess about your setup. 我只是猜测你的设置。

让PHP脚本检查$_SERVER['REMOTE_ADDR']是否为空,如果不是,那么让脚本退出而不做任何进一步的操作。

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. 在我的脑海中,我会说将它放在root拥有的目录中,只有root可读才可能接近达到你想要的效果。

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. 如果是这样,使用权限,使其不可读取任何这些进程。

我建议在crontab中设置一个环境变量,然后在PHP脚本中检查它

Create a user for cron jobs, and set permissions of the script so it can only be run as this user. 为cron作业创建用户,并设置脚本的权限,使其只能作为此用户运行。 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 . 当然,您需要将脚本放在该用户的crontab中 ,您可以通过以该用户身份登录并运行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. 起初我还在考虑设置一个环境变量来防止从网络上运行这个脚本...但是只是不将脚本放在Web服务器查找网站页面的空间中,也会这样做。

And nothing is stopping a random user from first setting the environment variable and then running the script. 并没有什么能阻止随机用户首先设置环境变量然后运行脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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