php写入数据到txt文件

时间:2022-09-21 19:07:31
<form action="index.php" method="post">
    <input type="text" name="user"/>
    <input type="text" name="password"/>
    <input type="submit" value="submit"/>
</form>
<?php
    $user=trim($_POST['user']);
    $password=trim($_POST['password']);
    if(!$user || !$password){
        echo 'please make sure no empty input';
        exit;
    }
    //write to test.txt
    $handle=fopen('test.txt','ab+');
    if($handle){
        $exits=false;
        while(($buffer=fgets($handle))!==false){
            $match=preg_match('/.*:(.*?)-/',$buffer,$array);
            //first write
            if(!$match){
                break;
            }

            //exist in txt
            if($match && $array[1]==$user){
                $exits=true;
            }
        }
    }else{
        echo 'fail to open file';
    }

    if(!$exits){
        fwrite($handle,'$user:'.$user.'-----'.'$password:'.$password."\r\n");
    }else{
        echo 'user exist';
    }
    fclose($handle);
?>