【问题标题】:Cron Job not recognising php arrayCron Job 无法识别 php 数组
【发布时间】:2012-01-29 04:19:25
【问题描述】:

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

<?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 作业没有将 $_____stack = json_decode(file_get_contents("_____.txt")); 解析为数组 - 我假设它会对 explode(); 做同样的事情;或类似的代替 JSON。

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

【问题讨论】:

  • cron 作业触发的目录不可能是同一个目录。使用 getcwd() 检查浏览器中的当前目录,并将其与 cron 作业中函数的输出进行比较。

标签: php cron


【解决方案1】:

这似乎是一个路径问题。 cronjob 作为系统进程运行,因此无法找到文件“colors.txt”和“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"));

希望对你有帮助!

【讨论】:

  • 由于某种原因,这并没有完全抓住它,但最后我通过在每个 file_get 和 file_put 命令中简单地包含完整路径来让它工作。干杯!
猜你喜欢
  • 2018-12-09
  • 2017-06-14
  • 1970-01-01
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多