Reputation: 215
I'm trying to set a persistent date stamp by writing it to a text file and then reading it back in each time the page is viewed.
// set the date, w/in if statements, but left out for brevity
$cldate = date("m/d/Y");
$data = ('clickdate' => '$cldate'); // trying to set a variable/value pair
- It's throwing an Error on this !
// Open an existing text file that only has the word "locked" in it.
$fd = fopen("path_to_file/linktrackerlock.txt", 'a') or die("Can't open lock file");
// Write (append) the pair to the text file
fwrite($fd, $data);
// further down …
// Open the text file again to read from it
$rawdata = fopen("path_to_file/linktrackerlock.txt", 'r');
// Read everything in from the file
$cldata = fread($rawdata, filesize("path_to_file/linktrackerlock.txt"));
fclose($rawdata);
// Echo out just the value of the data pair
echo "<div id='Since'>Clicks Since: " . $cldata['clickdate'] . "</div>";
Upvotes: 0
Views: 100
Reputation: 360802
Code's fundamentally broken. You're trying to create an array, then write that array out to a file:
$data = array('clickdate' => '$cldate');
^^^^^---missing
Then you have
fwrite($fd, $data);
But all that will do is write the word Array
out to your file, NOT the contents of the array. You can try it yourself... just do echo $data
and see what you get.
You could probably make this whole thing a lot simpler with:
$now = date("m/d/Y");
file_put_contents('yourfile.txt', $now);
$read_back = file_get_contents('yourfile.txt');
If you do insist on using an array, then you have to serialize or, or use another encoding format, like JSON:
$now = date("m/d/Y");
$arr = array('clickdate' => $now);
$encoded = serialize($arr);
file_put_contents('yourfile.txt', $encoded);
$readback = file_get_contents('yourfile.txt');
$new_arr = unserialize($readback_encoded);
$new_now = $new_arr['clickdate'];
Upvotes: 1
Reputation: 16828
$data = ('clickdate' => '$cldate');
needs to be:
$data = array('clickdate' => $cldate);
Additionally, you are required to pass a string to an fwrite
statement, so there is no need to create an array:
$cldate = date("m/d/Y");
if($fd = fopen("path_to_file/linktrackerlock.txt", 'a')){
fwrite($fd, $cldate);
fclose($fd);
}else{
die("Can't open lock file");
}
Upvotes: 3