0

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?

4
  • 2
    did you check file permission?
    – t q
    Apr 7, 2012 at 0:06
  • You should look to your error log there could be some interesting errors messages. Apr 7, 2012 at 0:07
  • are there any errors in your log? I assume you are executing the script on the cli and not requesting your server via cron. Are you maybe executing it from another location?
    – csupnig
    Apr 7, 2012 at 0:08
  • cron jobs generally always have a different default 'working directory', and will NOT be the directory that your script is running in. Since you've not specified a path on your fopen() call, the file will be created in whatever the cron environment's startup directory is. When a cron job has to do file operations, it's best practice to use absolute/full paths, not relative.
    – Marc B
    Apr 7, 2012 at 0:55

3 Answers 3

0

It's probably a permission problem. Try to chmod 777, and re-cron.

0

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;
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.