PHP在开头写一个文本文件

时间:2013-03-08 13:55:18

标签: php text-files fwrite

所以我们在课堂上制作了一种日志。有一个输入框和一个按钮。每次按下按钮,PHP都会在文本文件上写入并打印当前日志。现在文本显示在底部,我们需要将文本显示在顶部。现在我们该怎么做?

我们尝试与很多同学一起做这件事,但这一切都导致了奇怪的行为。 (就像文字打印一次,等等)

非常感谢!

编辑:对不起,这是代码:

<html lang="en">
<head>
    <title>php script</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <form name="orderform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">  
    <input type="text" name="text"/>
    <input type="submit" value="Submit" />
    <?php
        //Basic variables
        echo("<br/>");
        $myFile = "log.txt";
        $logfile = fopen($myFile,'r+');
        $theData = fread($logfile,filesize($myFile));

        //Cookie stuff so the username is rememberd.
        $username = $_COOKIE['gebruikerscookie'];;
        if(isset($_POST['username'])){
            $gebruiker = $_POST['username'];
            if($_COOKIE['gebruikerscookie'] == $gebruiker){
                $username = $_COOKIE['gebruikerscookie'];
                echo("Welcome back");
            }else{
                setcookie("gebruikerscookie", $gebruiker);
                $username = $_COOKIE['gebruikerscookie'];
                echo("Welcome dude!");
            }           
        }

        //Checks if theres something inside 
        if(isset($_POST['text'])){
            $message = "<br/>". $username ." : " . $_POST['text'];
            fwrite($logfile, $message ,strlen($message));
        }
        echo($theData);
    ?>
    </form>
</body>

4 个答案:

答案 0 :(得分:1)

查看型号上的fopen手册:http://www.php.net/manual/en/function.fopen.php

尝试'r+' Open for reading and writing; place the file pointer at the beginning of the file.

虽然没有任何代码,但这很难回答。

答案 1 :(得分:1)

<?php
$contentToWrite = "Put your log content here \n";
$contentToWrite .= file_get_contents('filename.log');
file_put_contents('filename.log', $file_data);
?>

这将在您当前的内容之后添加文件的先前内容并写入您的文件。

如果您有任何疑问,请回复。

答案 2 :(得分:0)

你只是错过了

fclose();

我认为,因为没有关闭文件句柄会导致很多像这样的奇怪错误。

所以

$myFile = "log.txt";
$logfile = fopen($myFile,'r+');
........
//Checks if theres something inside 
if(isset($_POST['text'])){
   $message = "<br/>". $username ." : " . $_POST['text'];
   fwrite($logfile, $message ,strlen($message));
}
fclose($logfile); // close it outside the if-condition!
echo($theData);

应该做的伎俩

答案 3 :(得分:-1)

$log = file('log.txt');
krsort($log);
foreach($log as $line) echo "$line<br>\n";