I’m using PHP and a Cron Job to dynamically update a stylesheet at regular intervals (for various reasons, Javascript isn’t an option). This is the script I’m running as a Cron Job:
<?php
$colorstack = json_decode(file_get_contents("colors.txt"));
$color = array_shift($colorstack);
file_put_contents("color.txt",$color);
array_push($colorstack, $color);
$colors = json_encode($colorstack);
file_put_contents("colors.txt", $colors);
$iconstack = json_decode(file_get_contents("icons.txt"));
$icon = array_shift($iconstack);
file_put_contents("icon.txt",$icon);
array_push($iconstack, $icon);
$icons = json_encode($iconstack);
file_put_contents("icons.txt", $icons);
print_r ($colorstack);
print_r ($iconstack);
?>
It returns strings from two text files (a set of hex codes, and a set of image filenames) and puts them into arrays. Then it grabs the first value from each array, writes them to a second set of text files (which are read by css.php), then sticks those values back onto the end of the arrays and writes them back to their text files.
Each time the script is executed, it spits up a new color hex code and image filename for the stylesheet, and sends the previous ones to the back of the loop. I’ve tested it, and it works fine in the browser.
The problem is that the Cron Job won’t execute the script. Instead, I keep getting the following:
Warning: array_shift() expects parameter 1 to be array, null given in /path/to/file.php on line 3
Warning: array_push() expects parameter 1 to be array, null given in /path/to/file.php on line 5
And so on. Obviously the problem is that the Cron Job is not parsing $_____stack = json_decode(file_get_contents("_____.txt")); as an array – and I’m assuming it would do the same for explode(); or similar in place of JSON.
Is there another relatively neat way to get the contents of those text files into arrays that won’t run into the same issue?
This seems to a path issue. The cronjob is run as a system process and is therefore not able to locate the files “colors.txt” and “icons.txt”.
But when you are executing the script in a browser, it automatically reads the files from the current folder.
The solution is to provide the full system path for the files in the cronjob. And in general always use full paths when doing any file read-writes in a cron script.
Here is a sample code:
Hope it helps!