简体   繁体   English

PHP - 从 Cron 作业/命令行调用脚本时环境变量不可用

[英]PHP - Environment Variables Not Available When Script Called From Cron Job / Command Line

My test.php file looks like:我的test.php文件看起来像:

<?php

echo $_SERVER["myEnvVariable"];
echo getenv("myEnvVariable");

The above will return my set environment variable twice.以上将返回我设置的环境变量两次。 It works when the script is called from outside the server.它在从服务器外部调用脚本时起作用。

If I call the same script on the server using the command line command:如果我使用命令行命令在服务器上调用相同的脚本:

php test.php

or using a cronjob或使用 cronjob

****** curl http://localhost/test.php

nothing is returned.什么都没有返回。

How do I make available my environment variables within the server itself?如何在服务器本身中提供我的环境变量? I am setting my environment variables within the Apache httpd.conf file.我正在 Apache httpd.conf文件中设置我的环境变量。

Execute the cron job this way:以这种方式执行 cron 作业:

myEnvVariable=value php test.php

Variable will be available from getenv("myEnvVariable") , not in $_SERVER .变量将从getenv("myEnvVariable") ,而不是在$_SERVER

Try setting wget to http://address.domain/test.php in cron.尝试在 cron 中将 wget 设置为http://address.domain/test.php I know this isn't solution but might help.我知道这不是解决方案,但可能会有所帮助。

If you are having lots of environment variables try this,如果你有很多环境变量试试这个,

Export env entries to a file将 env 条目导出到文件

env >> /etc/environment

Add the CRON job with crontab -e使用crontab -e添加 CRON 作业

5,35 * * * * . /etc/environment; /usr/local/bin/php /srv/app/artisan schedule:run >> /dev/null 2>&1

CRON : Running php scheduler at 05, 35 of each hour with source of all the environment variables. CRON :在每小时05、35 点运行 php 调度程序,并使用所有环境变量的来源。 (replace with your command) (替换为您的命令)

I suggest you to make a special curl call to your file.我建议您对您的文件进行特殊的 curl 调用。 Something like this:像这样的东西:

test.php (this is your file, no changes here) test.php (这是你的文件,这里没有变化)

specialcurl.php : specialcurl.php :

<?php
    $curl = curl_init('http://www.youraddresshere.com/pathtofile/test.php');
    curl_setopt($curl, CURLOPT_FAILONERROR, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($curl);
    echo $result;
    curl_close($curl);
?>

Now, run with php command the specialcurl.php script from the server as:现在,使用 php 命令从服务器运行 specialcurl.php 脚本:

php specialcurl.php

The point here is to call your test.php as a valid user calling your server.这里的重点是调用 test.php 作为调用服务器的有效用户。 It works for me.这个对我有用。

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

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