【问题标题】:php - Creating a file by running a script via cronphp - 通过 cron 运行脚本来创建文件
【发布时间】:2012-04-20 11:43:58
【问题描述】:

我已经编写了一个脚本来生成一些 XML,我使用一种非常基本的方法将 XML 的结果保存到一个文件中:

<?php
// start the output buffer to cache the content
ob_start();

//SOME PHP CODE HERE TO GENERATE CONTENTS ON THE FILE

$cachefile = "results.xml";
// open the cache file for writing
$fp = fopen($cachefile, 'w'); 
// save the contents of output buffer to the file
fwrite($fp, ob_get_contents()); 
// close the file
fclose($fp); 
// Send the output to the browser
ob_end_flush(); 

当我手动转到服务器上包含脚本的文件的 URL 时,脚本会运行并创建文件。

但是,当我尝试将其作为 cron 作业运行时,脚本会运行并且输出是通过不保存到文件来生成的。

有什么想法吗?

【问题讨论】:

  • 你检查文件权限了吗?
  • 您应该查看您的错误日志,可能会有一些有趣的错误消息。
  • 您的日志中有错误吗?我假设您正在 cli 上执行脚本,而不是通过 cron 请求您的服务器。您是否可能从其他位置执行它?
  • cron 作业通常始终具有不同的默认“工作目录”,并且不会是运行脚本的目录。由于您没有在 fopen() 调用中指定路径,因此文件将在 cron 环境的启动目录中创建。当 cron 作业必须执行文件操作时,最佳做法是使用绝对/完整路径,而不是相对路径。

标签: php cron


【解决方案1】:

正在创建文件,但位于根目录而不是运行脚本的目录。

在浏览器中运行的文件是在正确的目录下创建的,通过cron运行它是在根目录下创建的。

可能需要指定完整路径。

【讨论】:

    【解决方案2】:

    我可以想象,cronjob 只请求标头而不是正文,因此 apache 根本不会生成一个,因此 ob 保持为空...您可以尝试以下方法:

    <?php
    $out = ''
    
    //SOME PHP CODE HERE TO GENERATE CONTENTS ON THE FILE
    $out .= 'content' . "\n";
    $out .= 'more' . "\n";
    $out .= 'more' . "\n";
    $out .= 'more' . "\n";
    $out .= 'more' . "\n";
    
    $cachefile = "results.xml";
    // open the cache file for writing
    $fp = fopen($cachefile, 'w'); 
    // save the contents of output buffer to the file
    fwrite($fp, $out); 
    // close the file
    fclose($fp); 
    // Send the output to the browser
    
    print$out;
    

    【讨论】:

      【解决方案3】:

      这可能是权限问题。尝试 chmod 777,然后重新 cron。

      【讨论】:

        猜你喜欢
        • 2019-07-23
        • 2020-02-28
        • 1970-01-01
        • 1970-01-01
        • 2018-08-23
        • 2012-11-14
        • 2016-04-14
        • 2017-08-11
        • 2016-10-01
        相关资源
        最近更新 更多