【问题标题】:Appending multiple entries to an output file with a crontab using php?使用 php 将多个条目附加到带有 crontab 的输出文件?
【发布时间】:2014-10-09 03:31:53
【问题描述】:

我正在用 PHP 编写一个脚本,其中我必须将系统正常运行时间、当前时间和登录系统的用户数量写入日志文件,并通过 crontab 不断更新。

我需要帮助的是我希望在文件中累积更新并不断添加。到目前为止,每当我的脚本被执行时,最新的更新都会覆盖之前的更新。

我所做的是我尝试声明一个条目数组,并在我遍历数组时将更新的内容推送到数组中(这可能是我的一些半生不熟的逻辑)。

我的代码:

$fileName = '../so-and-so directory/output.log';
$dt = date('m/d/y');
$time = date('h:i A');
$data = shell_exec('uptime');
$uptime= explode(' up ', $data);
$uptime = explode(', ', $uptime[1]);
$uptime = $uptime[0].','.$uptime[1];
$users = system('w', $who);
$array = new SplFixedArray(3);



$fileLog = fopen($fileName, 'w');
$fileString = "Date: ".$dt. "\n". " Time: ".$time . "\n".
"System uptime ". $uptime ."\n" ."Users " . $users;

foreach ($array as $entry) {

 array_push(file_put_contents($fileName, $fileString));

}

fclose($fileLog);

我觉得解决方案很简单,但我错过了。有人请告诉我吗?

【问题讨论】:

  • 什么$array?它不存在
  • 在我尝试使用我的脚本时,这有点半生不熟的逻辑。我对 PHP 很陌生,所以这对我来说只是一个开始。

标签: php scripting crontab cron-task


【解决方案1】:

“w”文件模式会在打开文件时截断文件。 "a" 改为附加到末尾。有关详细信息,请参阅fopen(3) 或 PHP 文档。

另外,file_put_contents() 正在销毁文件。请改用fwrite()

【讨论】:

  • 还有比这个脚本破坏的更多的东西
【解决方案2】:

放下 fopen;只需使用

file_put_contents($fileName, $fileString);

file_put_contents 默认会覆盖现有文件。

简而言之:

$fileName = '../so-and-so directory/output.log';
$dt = date('m/d/y');
$time = date('h:i A');
$data = shell_exec('uptime');
$uptime= explode(' up ', $data);
$uptime = explode(', ', $uptime[1]);
$uptime = $uptime[0].','.$uptime[1];
$users = system('w', $who);

$fileString = "Date: ".$dt. "\n". " Time: ".$time . "\n".
"System uptime ". $uptime ."\n" ."Users " . $users;

file_put_contents($fileName, $fileString);

【讨论】:

    【解决方案3】:

    所以事实证明我需要像这样编辑我的 crontab 文件:

    * * * * * such-and-such-script.php >> ../so-and-so directory/output.log 2>&1
    

    使它们附加而不会被新的覆盖。我还丢失了 fopen(),而不是执行 file_put_contents,而是将 fwrite() 写入文件。现在效果很好。谢谢!

    【讨论】:

    • 只要调用脚本,cron 作业中的任何内容实际上都不会产生影响
    猜你喜欢
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 2015-11-10
    • 2021-09-23
    • 2017-03-20
    • 2011-09-09
    • 1970-01-01
    相关资源
    最近更新 更多