Cron作业无法识别php数组


Cron Job not recognising php array

我使用PHP和Cron Job定期动态更新样式表(由于各种原因,Javascript不是一个选项)。这是我作为Cron Job运行的脚本:

<?php
$colorstack = json_decode(file_get_contents("colors.txt"));
$color = array_shift($colorstack);
file_put_contents("color.txt",$color);
array_push($colorstack, $color);
$colors = json_encode($colorstack);
file_put_contents("colors.txt", $colors);
$iconstack = json_decode(file_get_contents("icons.txt"));
$icon = array_shift($iconstack);
file_put_contents("icon.txt",$icon);
array_push($iconstack, $icon);
$icons = json_encode($iconstack);
file_put_contents("icons.txt", $icons);
print_r ($colorstack);
print_r ($iconstack);
?>

它返回两个文本文件(一组十六进制代码和一组图像文件名)中的字符串,并将它们放入数组中。然后,它从每个数组中获取第一个值,将它们写入第二组文本文件(由css.php读取),然后将这些值粘贴回数组的末尾,并将它们写入它们的文本文件。

每次执行脚本时,它都会为样式表吐出一个新的颜色十六进制代码和图像文件名,并将以前的代码和图像发送到循环的后面。我已经测试过了,它在浏览器中运行良好。

问题是Cron作业不会执行脚本。相反,我不断得到以下信息:

警告:array_shift()要求参数1为数组,在第3行的/path/to/file.php中给定null

警告:array_push()要求参数1为数组,在第5行的/path/to/file.php中给定null

等等。很明显,问题是Cron Job没有将$_____stack = json_decode(file_get_contents("_____.txt"));解析为数组——我假设它对explode()也会这样做;或类似的方法来代替JSON。

有没有另一种相对简洁的方法可以将这些文本文件的内容放入不会遇到相同问题的数组中?

这似乎是一个路径问题。cronjob作为系统进程运行,因此无法定位文件"colors.txt"answers"icons.txt"。

但是,当您在浏览器中执行脚本时,它会自动从当前文件夹中读取文件。

解决方案是为cronjob中的文件提供完整的系统路径。通常,在cron脚本中执行任何文件读写操作时,都要使用完整路径。

这是一个示例代码:

$filePath = ''; // set it to full-path of the directory that contains the .txt files and terminate with a "/" (slash)
....
$colorstack = json_decode(file_get_contents($filePath . "colors.txt"));
....
$iconstack = json_decode(file_get_contents($filePath . "icons.txt"));

希望它能有所帮助!