Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this questionI am trying to verify the Username and Password that user enters are stored within a file, not a database. I have written only couple of usernames and passwords and put them in a file named testPass.fil and separated the username and passwords with tabs (\t).
My code seems to work if I test it to display the value of the username or password which I got out of the file by using the explode functi开发者_如何学Con. However, whenever I try to check the username and password the User entered on the login page against the ones stored in the file it gives me trouble. I tried using the echo statement to validate it and it gives me what appear to be the exact same strings but it doesn't execute the "If" statement which checks to see if they are equal. Sorry if there is a stupid or confusing question I've been working on this for awhile and I only know a little PHP. I will post the code below thanks for any help.
<?php
$userName=$_POST['userName'];
$userPass=$_POST['userPass'];
$correctPass=0;
$file=fopen("testPass.fil","r");
$record=fgets($file);
while(!feof($file))
{
$fileData=explode("\t",$record);
//echo "$fileData[0] <br> $userName <br><br> $fileData[1] <br> $userPass<br><br>";
//this line was used to make sure that the username entered and my stored username were the same.
if($userName==$fileData[0])
{
if($userPass==$fileData[1])
{
$correctPass=1;
break;
}
}
$record=fgets($file);
}
if($correctPass == 1)
{
echo "UserName and Password are present";
}
else
{
echo "The UserName or Password you entered is incorrect.";
}
fclose($file);
?>
You may need to strip white spaces from your username and passwords.
As Sinan says, you may need to strip whitespace from your strings before comparing them, say with the trim() function. You may also find it useful to run both the source and the comparison username strings through strtolower() to make the login check case insensitive.
Hmm, creating a basic ini-file and just calling parse_ini_file
on it would be a lot less hassle.
fgets
returns the entire line including the newline character at the end, you are not removing it so you are comparing "password"
and "password\n"
which are not equal.
You can fix it by stripping the newline character with rtrim()
each time you call fgets
:
$record = rtrim(fgets($file));
If you want to allow spaces in passwords you can also specify that it only remove carriage return and new line:
$record = rtrim(fgets($file, "\r\n"));
精彩评论