我正在尝试通过将其写入文本文件来设置持久日期戳,然后在每次查看页面时将其读回。
// 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>";
答案 0 :(得分:3)
$data = ('clickdate' => '$cldate');
需要:
$data = array('clickdate' => $cldate);
此外,您需要将字符串传递给fwrite
语句,因此无需创建数组:
$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");
}
答案 1 :(得分:1)
代码从根本上打破了。您正在尝试创建一个数组,然后将该数组写入文件:
$data = array('clickdate' => '$cldate');
^^^^^---missing
然后你有
fwrite($fd, $data);
但所有这一切都是将Array
写入您的文件, NOT 数组的内容。你可以自己试试......只需echo $data
看看你得到了什么。
你可以通过以下方式简化这一切:
$now = date("m/d/Y");
file_put_contents('yourfile.txt', $now);
$read_back = file_get_contents('yourfile.txt');
如果你坚持使用数组,那么你必须序列化或使用其他编码格式,如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'];