Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

fopen and fgets problem 1

Status
Not open for further replies.

doyle9732

Programmer
Apr 12, 2002
185
CA
I am trying to learn php, and this might be a stupid question, but I've searched my books and the internet and nothing seems to be giving me the answer.

I'm doing a login page. I've written the user information to a txt file and I see that it's delimited with a semi-colon. I can't seem to work around it, so I created a new variable that is made up of the user name and password with the semi-colon inbetween. When I echo the new variable it appears to be the same as the line in the file, but when I compare it in the if statement, if comes up as no match. Here is the code:

<?php
$UserInfo=$_POST["UserName"];
$PasswordInfo=$_POST["Password"];
$VarToTest="$UserInfo:$PasswordInfo";

$fp = fopen ("users.txt", "r");
$check=0;
while (!feof ($fp) && ($check == 0))
{
$content = fgets( $fp, 4096 );

if ($content == $VarToTest)
{
$check = 1;
}
else
{
$check = 0;
}
}

if ($check ==1)
{
echo "Welcome $UserName\n";
echo "<a href='shop.html'>go shopping</a>";
}
else
{
echo "sorry, your information does not match our records\n";
echo "<a href='login.html'>try again</a>";
}

fclose ($fp);
?>

can anyone share some light on this newbie?
many thanks!
Stephanie

 
Try
Code:
    if ($VarToTest == trim($content)) $check = 1;
When you read a line from a file, it comes in with the terminating "\n". The trim() function will remove that character.

Also, since you've already initialized $check to 0, you don't need the else clause.

I would actually initialize the variable to FALSE, so the whole sequence would be:
Code:
$check = FALSE;
while (($content = fgets($fp, 4096)) != FALSE)
{ 
    if ($content == $VarToTest) {
        $check = TRUE;
        continue; }
}
fclose ($fp); 

if ($check)
    echo 'Welcome ' . $UserName. "<br>\n" . '<a href="shop.html">go shopping</a>';
else
    echo 'Sorry, your information does not match our records<br>'."\n".'<a href="login.html">Please try again</a>';
As you can see, I shorted up the code a little. You don't need the braces "{ }" when the code block after an if statement is one line.

Of course, storing unencrypted passwords in a text file is asking for trouble. [sad]

Hope this helps a little.

Ken
 
Ken, you are a superstar!

I'm following a tutorial and I think I learn about databases in the next section.

thank you, Thank You, THANK YOU!
Stephanie
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top