PDA

View Full Version : php script doesn't behave when called via cron



rycharn
05-04-2009, 12:26 AM
I want my php script to update (append) a text file (log.txt) when the script executes. It runs fine when it is called from a browser, but not when cron runs it. Permission is set at 755. Here's a simplified version of my script:

#!/usr/local/bin/php

<?php

$newline=chr(10);
$now=time().$newline;

$handle=fopen("log.txt", "a+");
fwrite($handle, $now);
fclose($handle);

?>


I have also tried a version with "echo $now();" before the closing tag, which causes cron to send me an email with the output of the script. The email has the expected result, so I know there's nothing wrong with the variable, and I know the script is executing.

I've also tested the script with "file_exists" and "is_writable" variations; the script sees the file, and considers it writable. If I substitute "$result=fwrite($handle, $now);" I get a result. The script clearly thinks it is updating log.txt, but when I check that file, it is unchanged.

Again, when I execute the same script from a browser, it works fine -- the log.txt file is appended. Any ideas why it fails to function when cron runs it?

felgall
05-04-2009, 01:09 AM
scripts run via cron use a default path three directories higher than those run directly from a web browser.

You don't have access to write to that directory as it is two levels above your account.

If you use the path to your site to tell it where towrite the file you should be able to resolve the issue. The top level directory name will be home possibly with a number after it. The second level will be your 8 character account name. You should be able to find both values in the info on the left of your cpanel home page.

rycharn
05-04-2009, 09:18 AM
Thanks, felgall, it works. I'm sure you knew it would. I think I might have eventually figured out the file path issue myself, if it weren't for the positive results I got when I tested with "file_exists" and "is_writable". However, I know I wouldn't have understood why the longer path is necessary. I appreciate your explanation; I'm much happier when my understanding goes beyond "how" to "why".