2017-04-19 28 views
0

我想以這樣的方式編寫代碼,它會將任何輸入寫入並保存在.TXT文件中。那麼應該有一些功能會搜索整個文件(txt),如果之前已經寫入或保存過文本或單詞,則會帶來錯誤。沒有重複的PHP fwrite

如果有人寫愛和其他人想輸入的愛再次,它應該帶來的錯誤信息。

這裏是我的代碼

<?php 
$name=$_POST['name']; 
$myfile= 
fopen("man.txt" , "a+") or 
die("Unable to open file!"); 
fwrite($myfile, "Name:".$name. "\r\n") 
?> 
+1

什麼碼/方法你試過這麼遠嗎? – Hunter

+0

這是另一個代碼<?php $ name = $ _ POST ['name']; if(empty($ name)) { echo「Please enter your name」; } else $ name = $ name; $ MYFILE = 的fopen( 「mam.txt」, 「A +」)或 模具( 「無法打開文件!」); $ path =「mam.txt」; 如果(file_exists($路徑)) { \t $內容的file_get_contents =($路徑); \t $ contents = explode(「\ r \ n」,$ contents); \t $ users = array(); foreach($ contents as $ value){ \t $ user = explode(「\ r \ n」,$ value); \t $ users [$ user [0]] = isset($ user [1])? $ user [1]:null;如果(isset($ users [$ _ POST ['name']])) { echo「Name exists」; } else echo「NO」; } 的fwrite($文件MyFile,$名字。 「\ r \ n」) ?> – SOA

回答

1

在這裏,我使用了in_array函數來檢查提交的名字我們已經填充的數組($users)。

如果找不到名稱,是回聲「名稱存在」。如果沒有找到它,回聲「否」並添加名稱。

<?php 

$name = $_POST['name']; 
if (empty($name)) { echo "Please enter your name"; } else $name=$name; 

$myfile= fopen("mam.txt" , "a+") or die("Unable to open file!"); 

$path="mam.txt"; 

if (file_exists($path)) { 
    $contents = file_get_contents($path); 
    $contents = explode("\r\n", $contents); 

    $users = array(); 

    foreach ($contents as $value) { 
     $users[] = $value; 
    } 
    // Search the file for the submitted name 
    if (in_array($name, $users)) { 
     // The name already exists 
     echo "Name exist"; 
    } else { 
     // The name doesnt exist 
     echo "NO"; 
     // Add the new name 
     fwrite($myfile, $name. "\r\n"); 
    } 
} 
?> 
+0

非常感謝您! – SOA

+0

非常感謝。有效。如果我在TeX字段中沒有任何內容刷新頁面,它會告訴我名稱存在。它將空白空間視爲數組。幫幫我 – SOA