2012-08-14 81 views
0

我剛剛開始從互聯網學習,我很新。我看到了一些文件處理的例子。但是,當我按照文件的相同步驟時,它不起作用。獲取用戶輸入到php文件

閱讀功能是工作文件。但寫入文件不起作用。我也試過用file_put_content函數來寫。 :(

<?php 
    if(isset($_POST['submit1'])){ 
    $fileName = "Text.txt"; 
    $fh = fopen($fileName,"a") or die("can not open the file to write"); 

    //Writing to a file 
    $newData = "Hello This is new Data"; 
    fwrite($fh,$newData); 
    fclose($fh); 

    //Reading a file -- Working 
    $text = fopen("Text.txt","r") or die ("can not open the file to read");  
    while(!feof($text)) 
    { 
     $myLine = fgets($text); 
     print $myLine; 
    } 
    fclose($text); 
    } 

?> 

請指導我.. 感謝

+0

它不工作,因爲它顯示「無法打開文件寫入「? – 2012-08-14 09:37:48

+0

你應該檢查你的文件夾/文件的權限 - 帳戶是否有權訪問該文件來寫?發佈您收到的錯誤消息以幫助確定問題。 – Fluffeh 2012-08-14 09:38:19

+0

是的,此消息出現在文件寫入部分。但在文件閱讀的情況下,它工作正常。 – 2012-08-14 09:39:19

回答

1

這工作得很好,什麼是你的錯誤

<?php 
    $file = 'text.txt'; 
    $writer = fopen($file, 'a'); 
    $addData = 'This is a new string to be added at the end of the file'; 
    fwrite($writer, $addData); 
    fclose($writer); 
    ?> 

EDIT1: 從郵寄進境的輸入要求,您可以做這樣的事情:

<?php 
     if ($_SERVER['REQUEST_METHOD'] == 'POST'){ 
     $addData = $_POST['input-name']; 
     $file = 'text.txt'; 
     $writer = fopen($file, 'a'); 

     fwrite($writer, $addData); 
     fclose($writer); 
     } 
    ?>