简体   繁体   English

php - 通过 cron 运行脚本创建文件

[英]php - Creating a file by running a script via cron

I've written a script to generate some XML, im using a very basic method to save the results of the XML to a file:我写了一个脚本来生成一些 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(); 

When I manually go to the URL of the file containing the script on my server the scripts runs and creates the file.当我手动将 go 更改为服务器上包含脚本的文件的 URL 时,脚本将运行并创建文件。

However, when I try and run it as a cron job the script runs and the output is generated by not saved to a file.但是,当我尝试将其作为 cron 作业运行时,脚本会运行并且 output 是通过未保存到文件而生成的。

Any ideas why?任何想法为什么?

It's probably a permission problem.这可能是一个权限问题。 Try to chmod 777, and re-cron.尝试 chmod 777,然后重新 cron。

I could imagine, that the cronjob only requests the header and not the body, so that the apache simply does not generate one so that ob stays empty... Can you try something of the following:我可以想象,cronjob 只请求 header 而不是主体,因此 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;

File is being created but in the root rather than the directory where the script was being run.正在创建文件,但在根目录中,而不是在运行脚本的目录中。

Run in the browser file is created in the correct directory, run via cron and it is created in the root.在浏览器中运行文件在正确的目录中创建,通过 cron 运行并在根目录中创建。

Probably need to specify the full path.可能需要指定完整路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM