0

我正在我的网站上写一个评论块。我将评论保存在文件中并将内容打印在

网页。但问题是当我最后一次刷新网页时

评论显示两次。

所以我使用了一个逻辑,即我在我的评论数据库文件中搜索最后一条评论,如果它发现它没有写在文件上。

这是我的代码

<html>


<body>

<form   method="GET">

<textarea rows="15" cols="50" name="comments" ></textarea>
<input type="submit" value="submit" >

</form>

</body>

</html>




<?php
$refresh = 0;

$comments = file_get_contents("comments.txt");
$file_comments_len = strlen($comments);

$current_comments = $_GET["comments"];
$current_comments_len = strlen($current_comments);


for($i = 0; $i<= $file_comments_len; $i++){

    $sub = substr($comments, $i, (($i+$current_comments_len-1 )) ); 
    echo $sub."<br>";
    echo $i;
    if( $sub == $comments){
        $refresh = 100;
        break;
    }

}

if( ($_GET["comments"]!=null) && ($refresh==0) ){
    $comments = /*"Anonymous said:<br>".*/$_GET["comments"]."<br><br>";
    //$file_comments = fopen("comments.txt","a");
    //fwrite($file_comments,$comments);
    //fclose($file_comments);
    file_put_contents( "comments.txt", $comments, FILE_APPEND );

    $_GET["comments"] = null;
    $comments = null;

}

//$file_comments2 = fopen("comments.txt", "r");
$comments = file_get_contents("comments.txt");
echo $comments;
//fclose($file_comments2);

$_GET["comments"] = null;
$comments = null;

?>
4

1 回答 1

0

您只需尝试更改变量名称,例如 $comments 使用了两次以上。

if( ($_GET["comments"]!=null) && ($refresh==0) ){
$comments_new = /*"Anonymous said:<br>".*/$_GET["comments"]."<br><br>";
//$file_comments = fopen("comments.txt","a");
//fwrite($file_comments,$comments);
//fclose($file_comments);
file_put_contents( "comments.txt", $comments_new, FILE_APPEND );
$_GET["comments"] = null;
$comments_new = null;
}

这可能有帮助!

于 2012-11-17T09:12:41.240 回答