0

我试图通过将其写入文本文件然后在每次查看页面时将其读回来设置持久日期戳。

// 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>";
4

2 回答 2

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");
}
于 2012-12-21T16:03:06.110 回答
1

代码从根本上被破坏了。您正在尝试创建一个数组,然后将该数组写入文件:

$data = array('clickdate' => '$cldate');
        ^^^^^---missing

然后你有

fwrite($fd, $data); 

但所做的只是将单词写入Array您的文件,而不是数组的内容。您可以自己尝试一下...只是做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'];
于 2012-12-21T16:08:46.697 回答