2013-03-08 80 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