PHP脚本无法识别匹配的字符串

时间:2017-11-13 20:33:45

标签: php forms file

我正在尝试编写一个php脚本,它将滚动文本文件中的字符串列表,并将每个字符串与html表单中的用户输入进行比较。 如果找到匹配项,则应将用户输入的字符串发布到屏幕上。不知何故,尽管存在相同的字符串,但两个字符串之间的比较永远不会产生匹配。

这是php代码

<?php
session_start();
$myFile = "usernamelist.txt";

if (isset($_POST['originaluserid'])){//verifies the creation user input from the html page(for users signing up for the first time)
    $userid = $_POST['originaluserid'] . PHP_EOL;
    $fh = fopen($myFile, 'a') or die("can't open file");    
    fwrite($fh, $userid);
}

if(isset($_POST['userid'])){//verifies the existence of username information for an old user logging back in
    $userid = $_POST['userid'];
    $fh = fopen($myFile, 'r');
}

$theData = fgets($fh);  

$_SESSION['id'] = $userid;//so that userid can be called in another page

if ($fh) {
    while (($line = fgets($fh)) !== false) {
        if($userid == $theData){//errors in matching input with collected data in text file
            echo "<html>
            <head></head>
            <body>
            <p>the ID of the user is: $userid</p> <!--I want userid to be displayed here-->
            <p>welcome to My Shopping Page</p>
            </body>
            </html>";
            exit;
        }
    }
    fclose($fh);
} else {
    echo "error";
    exit;
} 

echo "access not granted";
?>

这是html代码

<html>
<head></head>
<body>
<form action="myshopping.php" method="post">
Log in with User ID:
<input type="text" name="userid">
<br>
<input type="submit">
<br>
Sign up for a brand new account:
<input type="text" name="originaluserid">
<br>
<input type="submit">
</form>

</body>
</html>

以及文本文件中的所有内容(&#34; usernamelist.txt&#34;)是:

username1
username2
username3
username4

1 个答案:

答案 0 :(得分:3)

首先,您使用变量$theData而不是变量$line。此外,fgets不会删除包含换行符的空格字符,因此您需要使用trim。试试这个,看它是否有效:

if (trim($userid) == trim($line)) {

您还需要删除$theData = fgets($fh);,因为它抓取第一行并且不会使用上述逻辑进行检查。

相关问题