Page 1 of 1

function to log in users off a delimited text file

Posted: Tue Dec 06, 2011 2:35 pm
by cturcotte224
Hi all. I am new to PHP and I am working on a class assignment. The assignment is to grab a user name and password off a form, pass it to a function that compares it to user information in a text file, then returns true if the user name and password match an entry in the text file, or returns false if there is no match. I know in the real world a database would be used for this, but as I said this is the assignment.

The text file is set up like this:
user:pass:first_name:last_name

With multiple users listed.

I got the function mostly written, however It only returns true if you enter the first user's information. If you enter the second user's information, it will match it on the second loop, but still return false. Any help on this would be great, Thank you. I posted my function below.

Code: Select all

<?php

function getLogin($username, $password)
{
        $fp_open=fopen("registered_users.txt", "r");//read file in

	if(!$fp_open)
	{
		echo "Sorry, I failed and cannot find this file. Please try again later!<br/>";
		exit();
	}

	if($fp_open)
	{
		while(!feof($fp_open))
		{
			$user_info=fgets($fp_open);

			for($i=0; $i<count($user_info); $i++)
			{
				$line=explode(":", $user_info);

				$user= $line[0];
				$pass=$line[1];

                                if($username==$user && $password==$pass)
				{
                                       return true;
					break;
				}
				else
				{
					return false;
				}
			}
		}
	}
}
?>

Re: function to log in users off a delimited text file

Posted: Tue Dec 06, 2011 3:04 pm
by maxx99
This only gets one line:

Code: Select all

      $user_info=fgets($fp_open);

So that doesn't make sense right now:

Code: Select all

       for($i=0; $i<count($user_info); $i++)
                         {
Check "Example #1 Reading a file line by line" on this url:
http://php.net/manual/en/function.fgets.php

Re: function to log in users off a delimited text file

Posted: Tue Dec 06, 2011 3:19 pm
by cturcotte224
Ok, so I would need to use a while loop to loop through each line of the file?

Re: function to log in users off a delimited text file

Posted: Wed Dec 07, 2011 2:33 am
by maxx99
:) yep, like you've said