简体   繁体   中英

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:

<?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.

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.

Any ideas why?

It's probably a permission problem. Try to chmod 777, and re-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:

<?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.

Probably need to specify the full path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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