2013-03-08 49 views
1

所以我们在这个类中创建了一种日志。有一个输入框和一个按钮。每次按下该按钮时,PHP都会在文本文件上写入并打印当前日志。现在文字出现在底部,我们需要让文字出现在最上面。现在我们该怎么做?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> 

+0

我的猜测是,你正在使用** A ** **或A + **用'fopen()函数'打开日志时,你应该使用** r + **代替''r +'\t开放供阅读和写作;将文件指针放在文件的开头.' – HamZa 2013-03-08 13:57:38

+0

添加了代码对不起 – Dallox 2013-03-08 15:28:15

回答

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.

Altough无需任何代码,这是很难回答。

+0

Tis不起作用。 – 2013-03-08 13:59:13

+0

你是什么意思?这将工作得很好 – 2013-03-08 13:59:58

+0

添加了代码对不起 – Dallox 2013-03-08 15:28:45

-1
$log = file('log.txt'); 
krsort($log); 
foreach($log as $line) echo "$line<br>\n"; 
1
<?php 
$contentToWrite = "Put your log content here \n"; 
$contentToWrite .= file_get_contents('filename.log'); 
file_put_contents('filename.log', $file_data); 
?> 

这将您cureent内容后添加文件以前的内容,并在你的文件写。

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

+1

这是一个理智的。 – 2013-03-08 14:03:19

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); 

应该做的伎俩

+0

没有关闭它,它给了我0错误。但这不是关于错误。我希望我的文本文件从下到上排列。 – Dallox 2013-03-08 15:52:44

+0

好吧,你说的很奇怪。这是一个错误。当然不是用于php脚本(它并不太在意),但对你来说是这样。 – itsid 2013-03-09 11:11:58