2015-02-06 85 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