简体   繁体   English

确保php脚本仅在本地运行

[英]Making sure php script is only run locally

I am running a PHP script via linux cronjob and I want to make sure that it can be run remotely only from the computer whose ip address I specify, plus via cronjob. 我正在通过linux cronjob运行PHP脚本,我想确保它只能从我指定的IP地址的计算机远程运行,再加上通过cronjob。 Now, I can check the remote ip addresses from $_SERVER['REMOTE_ADDR'] , but doing so would also stop execution via cronjob.So, how to make both things work? 现在,我可以从$_SERVER['REMOTE_ADDR']检查远程IP地址,但这样做也会通过cronjob停止执行。所以,如何让两件事都有效?

Put the cronjob out of your web root. 将cronjob移出您的网络根目录。

Then you can check wheather the cron is running over a cli: 然后,您可以检查cron是否在cli上运行:

if (php_sapi_name() != 'cli') {
    die();
}

Its no good idea to tun your cron over your webserver. 在您的Web服务器上调整Cron并不是一个好主意。 Then every people can start it. 然后每个人都可以启动它。

You'll need to check if it is run from the command-line too to handle the cron case 您还需要检查它是否也从命令行运行以处理cron情况

if (php_sapi_name() == 'cli' || $_SERVER['REMOTE_ADDR'] == 'your.ip.add.ress') {
    // allow
}

You can use php_sapi_name function to check for local (cron) execution in addition to checking IP addresses, something like this: 除了检查IP地址之外,您还可以使用php_sapi_name函数检查本地(cron)执行,如下所示:

if (php_sapi_name() == 'cli' || $_SERVER['REMOTE_ADDR'] == 'xxx.yyy.zzz.vvv') {
    //do your stuff
}
else {
    /show some error
}

That said, you need to remember that remote address can be easily spoofed, therefore it's not good to rely on it, at least if the server is open to the internet. 也就是说,你需要记住,远程地址很容易被欺骗,因此依赖它是不好的,至少如果服务器是对互联网开放的话。 It's a bit more secure if you're running on a local network. 如果您在本地网络上运行,它会更安全一些。

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

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