2015-02-06 82 views
0

你好我的代碼有問題,即時通訊嘗試讀取myfile的特定值,如果找到值,它將只從文件中刪除該文本值並繼續。繼承人我得到了:Aut是我有的形式的一部分,如果在文本文件中找到表單中鍵入的值,它將回寫到該文本文件,如果沒有,它將回顯無效令牌。所有的幫助表示讚賞。某些文本的PHP檢查文件

<?php 

$myfile = "Variables.txt"; /**This part defines my file holding the keys**/ 
$lines = file($myfile); 
$fn = "DropBox/Dropbox/Public/Licenses.txt"; /**this is where addition/aut are written**/ 
$file = fopen($fn, "a+"); 
if(!($fd = fopen("Variables.txt","w"))) 
    die("Could not open $file for writing!"); 


if(!(flock($fd,LOCK_SH))) 
    die("Could not equire exclusive lock on $file!"); 


for($i = 0; $lines[$i]; $i++) 
{ 
if($_POST['Aut'] == rtrim($lines[$i])) /** if the input value in Aut is found in Variables.txt, only that line will be deleted **/ 
{ 
    fwrite($file, $_POST['addition']."\n\t"); /** writes addition which is an input variable to the file $file **/ 
    fwrite($file, $_POST['Aut']."\n\t"); /** the Aut removed from $myfile is also written to $file **/ 
} 
else 
{ 
    echo "Invalid Code"; /** if the codes is invalid, then this is echoed **/ 
} 
} 

if(!(flock($fd,LOCK_UN))) 
    die("Could not release lock on $file!"); 

if(!(fclose($fd))) 
    die("Could not close file pointer for $file!"); 
?> 
+0

請解釋你的代碼當前做錯了什麼。 (它看起來像你可以更好地使用數據庫) – mario 2015-02-06 05:30:35

+0

我所有的代碼正在訪問我希望它訪問的文件,但它會自動刪除所有內容,並回顯10次無效的代碼。我不知道如何使用數據庫如何做 – 2015-02-06 05:36:06

+0

嗯,它寫後確認密鑰,所以它的作品,但它刪除我的文件 – 2015-02-06 05:39:08

回答

-1

在文件中逐行迭代可能不是最好的方法。相反,只使用file_get_contents在一次閱讀:

$text = file_get_contents("Variables.txt"); 

再看看只用一個正則表達式替換線(preg_match第一,甚至只是preg_replace在這兩種情況下)從輸入變量:

// prepare for literal regex matching 
$aut = preg_quote($_POST["Aut"], "/"); 

// check for matching line 
if (preg_match("/^$aut\s*$/m", $text)) { 

    // Remove line and update file 
    $file = preg_replace("/^$aut\s*$/m", "", $text); 
    file_put_contents("Vars.txt", $file, LOCK_EX); 

    // Write new vars to second text file 
    file_put_contents("File2.txt", "$Aut \n $Add \n", FILE_APPEND|LOCK_EX); 
} 

else { 
    // Token not found 
} 

這隻會取代真正以$aut開頭的行,並讓所有其他事情獨自一人。

請注意,您仍然應該同時打開兩個文件,其中LOCK_SH可讀並且與LOCK_EX更新爲file_put_contents。 (我不打算詳細說明,因爲這是一個問題你已經選擇有。)

+0

所有其他的東西,我不想要爲了替換任何文字,我瘋了,讓我更好地解釋一下自己。確定即時閱讀文件Variables.txt並寫入$文件,這是另一個.txt文件。如果我的輸入中的變量在我的Variables.txt中找到。然後只有那個文本被刪除,然後Addition和Aut被寫入到$ file – 2015-02-06 05:49:11

+0

那麼使用preg_match(preg_replace的空替換文本),而不是將新的輸入變量寫入單獨的文件。 – mario 2015-02-06 05:50:49

+0

嘿,對不起,我有點小菜,你能寫出新代碼的樣子嗎? – 2015-02-06 05:53:23