Php检查某个文本的文件

时间:2015-02-06 05:26:13

标签: php

你好我的代码有问题,我试图读取myfile的特定值,如果找到值,它将只从文件中删除该文本值并继续。以下是我得到的:Aut是我拥有的表单的一部分,如果在文本文件中找到表单中键入的值,它将写回该文本文件,如果不是,它将回显Invalid Token。所有帮助表示赞赏。

<?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!");
?>

1 个答案:

答案 0 :(得分:-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_EXfile_put_contents更新并行打开两个可读文件和LOCK_SH文件。 (我不打算详细说明,因为这是你已经选择的问题。)