我正在运行OS Ububtu 16.04。我的最终目标是能够每分钟将 PHP 脚本作为 cron 作业运行。这是位于/var/www/html/Tests/Test/index.php
的PHP脚本:
<?php
$directoryPath = $_SERVER['DOCUMENT_ROOT']."/Tests/Test/data/";
echo "directoryPath: $directoryPath<br><br>";//check
$imageFilePathsArray = glob($directoryPath . "*.{png,gif}", GLOB_BRACE);
echo "<br><br>imageFilePathsArray: "; print_r($imageFilePathsArray);//check
?>
当我通过访问 URLMY-IP-ADDRESS/Tests/Test/index.php
在浏览器中打开此 PHP 脚本时,我得到:
directoryPath: /var/www/html/Tests/Test/data/
imageFilePathsArray:Array( [0] => /var/www/html/Tests/Test/data/pic.png [1] => /var/www/html/Tests/Test/data/pic.gif )
在我的 cronTab 文件中写入 cron 作业之前,我需要检查我是否可以使用终端从任何地方运行它。所以我在/home/
位置打开了 Ubuntu 终端,并在终端中执行:
sudo php /var/www/html/Tests/Test/index.php
我得到了以下输出:
directoryPath: /var/www/html/Tests/Test/data/
imageFilePathsArray: Array (
)
问题是,为什么当从命令行运行相同的脚本时,我得到一个空数组,而当它从浏览器运行时,我得到一个完全填充的数组?
通过 CLI 运行脚本时不能使用$_SERVER['DOCUMENT_ROOT']
。
$_SERVER['DOCUMENT_ROOT']
(就像大多数$_SERVER
参数一样(由 Web 服务器填充。当您通过 CLI 运行脚本时,永远不会涉及 Web 服务器,因此不会设置该参数。