• Sign in to Neowin Faster!

    Create an account on Neowin to contribute and support the site.

  • 0
Sign in to follow this  

[PHP] Login using data from a text file

Question

Ryan2g    0

I'm trying to make an online shopping site, where users can make an account, and login using the details they entered on the form page.

I've only managed to make it validate the information the user has entered on the form page, and it saves the data into a users.txt using a " : " to seperate each data information, so for example in the users.txt it would be like this:

email : firstname : surname : age

Now, I want to be able to use the log in boxes on the homepage with this users.txt. And it matches the username and password in the users.txt and lets them login.

Problem is, I actually don't have a clue where to begin for that.

Another problem is, if I'm reading from the users.txt file, how can I make it search line by line, and match the username and password on the same line, instead of it trying to search the entire users.txt file and possibly finding a matched password somewhere else.

Any help would be appreciated, thanks.

*EDIT* Also, is there a way to only have one instance of an email to be registered in the text file? So that not more than one email can be used/saved?

Share this post


Link to post
Share on other sites

15 answers to this question

Recommended Posts

  • 0
bolerodan    1

Im just curious, why do you want to use a flat text file for this? I would think an SQL database would be much easier to accomplish what you are trying to do.

Share this post


Link to post
Share on other sites
  • 0
Ryan2g    0

It's for an assignment, I have to use a flat text file.

Also, would I have to somehow use the explode function and make use of arrays in order for this to work?

I just need something that can help me get started off.

Share this post


Link to post
Share on other sites
  • 0
bolerodan    1

ohh okay, well if its for an assignment, fair enough then.

Now you are right, you will have to use the explode function in PHP. Its quite simple really. Once you read in a line from the file, you can use the explode function and pass in what character to explode the string by, which then stores them into an array.

so once you read a line in from the file, store that line into a variable, then use Explode on it with your specified character to explode by, in your case the colon

$userData = explode(":",$stringFromFile);

now explode split the string into two seperate pieces and stores them into the $userData variable as an array so you can easily access them via

//username //password

echo $userData[0] . $userData[1];

granted this is just rough, you'll have to google up how to loop through the file line by line, exploding, comparing, etc.

Edited by bolerodan

Share this post


Link to post
Share on other sites
  • 0
primexx    372

i'm assuming your user would be asked for all four pieces of the information in the form.

if that's the case you may want to - instead of searching for their email and then matching the rest of the stuff one-by-one - concatenate all the input into a string with the same format as the entry would have in the txt file, and search to see if the string exists in the file.

$email = "blah@bleh.com";

$firstname = "john";

$surname = "doe";

$age = "35";

$login_info = "$email : $firstname : $surname : $age";

$file = // read the txt file in as a string;

if (stristr($file,$login_info)) {

// login

}

else {

// don't login

}

edit: damn i envy you...I'm stuck with python because i'm in an intro class for easy credits :p

Share this post


Link to post
Share on other sites
  • 0
Ryan2g    0

Thanks for your reply guys, but there's just one thing that is stopping me, I have no idea how to make it read only one line. :(

It's probably something simple that I'm missing...

I have it writing to my users.txt file like this:

		$output = $firstname. " : ";
		fwrite($fh, $output);

		$output = $surname. " : ";
		fwrite($fh, $output);

		$output = $age. " : ";
		fwrite($fh, $output);

So you can see, they are seperated with " : ". So it's saved it as "firstname : surname : age" And if another user registers, it creates a new line and again does the "firstname : surname : age".

But simply reading one line at a time to try and match it with what's entered in a username and password field, it's most likely something simple I'm missing though.

I understand how to use the explode, etc. But reading just one line, I'm stumped on.

Share this post


Link to post
Share on other sites
  • 0
AnthonySterling    11

You could simplify this into a 2 functions, once to create records, and another to compare them.

<?php

#always use same file for logins
$user_accounts_file = 'logins.txt';

#create a few user accounts (once only)
create_user($user_accounts_file, 'admin', 'secretpassword');
create_user($user_accounts_file, 'moderator', 'secretpassword');
create_user($user_accounts_file, 'user', 'secretpassword');

#test if an account exisits with username 'admin' and password 'secretpassword'
if(true === check_user($user_accounts_file, 'admin', 'secretpassword'))
{
	echo 'Authorised';
	exit;
}

Functions

/**
 * @param string $user_accounts_file
 * @param string $username
 * @param string $password
 * @return boolean
 */
function create_user($user_accounts_file, $username, $password)
{
	if(false === file_exists($user_accounts_file))
	{
		trigger_error(
			sprintf(
				'The $user_accounts_file does not exist at the specified location: %s ',
				$user_accounts_file
			),
			E_USER_ERROR
		);
		return false;
	}
	return (bool)file_put_contents(
		$user_accounts_file,
		sprintf(
			"%s|%s|%s\r\n",
			sha1(uniqid()),
			$username,
			$password
		),
		FILE_APPEND
	);
}

/**
 * @param string $user_accounts_file
 * @param string $username
 * @param string $password
 * @return boolean
 */
function check_user($user_accounts_file, $username, $password)
{
	if(false === file_exists($user_accounts_file))
	{
		trigger_error(
			sprintf(
				'The $user_accounts_file does not exist at the specified location: %s ',
				$user_accounts_file
			),
			E_USER_ERROR
		);
		return false;
	}
	foreach(file($user_accounts_file) as $entry)
	{
		list($entry_key, $entry_username, $entry_password) = array_map('trim', explode('|', $entry));
		if($entry_username === $username && $entry_password === $password)
		{
			return true;
		}
	}
	return false;
}
?>

Share this post


Link to post
Share on other sites
  • 0
Ryan2g    0

Thanks for your reply, but I'm not sure as how what is in the username and password fields is compared to what's in a line of the users.txt

*EDIT* I'm thinking of something like, getting what's entered in the username and password, re-saving the values into a $var, then comparing it with the exploded strings?

Share this post


Link to post
Share on other sites
  • 0
AnthonySterling    11

That's exactly what it does. :D

		list($entry_key, $entry_username, $entry_password) = array_map('trim', explode('|', $entry));
		if($entry_username === $username && $entry_password === $password)

Share this post


Link to post
Share on other sites
  • 0
Ryan2g    0

I'm so confused with your piece of code SilverBulletUK, lol. :(

Any other simplier ways? Or can you explain step by step?

I've experimented with the print_r(); I did this just for a small printing test to check whether my explode is working correctly, it prints:

Array ( [0] => asdf@asdf.com [1] => Ryan [2] => 2g [3] => 18 [4] => 123 test [5] => 12345 )

But then the next line would start off with "Array ( [0] =>" again, is this normal? Or I am I supposed to use a for loop to increase the index?

Share this post


Link to post
Share on other sites
  • 0
bolerodan    1

For that check_user function it is used to determine if the supplied information already exists in the text file or actually.. to match the username and password together. So that function takes in the path to the text file holding the users, and the username / password grabbed from the Form that the user submits.

The function returns TRUE when a matched entry is found. Essentially he is using the PHP function file() storing each line of the file into an array within the FOREACH loop. Assigns it to $entry variable, and loops through the entire array comparing and matching.

You have to use some sort of loop to go through the entire file, and he is using a foreach loop then testing each case, moving on to the next. If he finds a matched entry, the function returns true. And if it returns true, depending on what you are doing (checking for password, checking if a user already exists) you can then use Logic to do the next steps.

take a look at the php file() function http://ca.php.net/manual/en/function.file.php

I recommend you use this site for everything you need. Learn all the PHP functions, read up on how to loop through a text file grabing each line. But his example here does just that

Share this post


Link to post
Share on other sites
  • 0
primexx    372

you don't have to do any exploding or reading line by line if you use my method. is that prohibited by the assignment guidelines?

Share this post


Link to post
Share on other sites
  • 0
Ryan2g    0

I'll give that a method a shot right now then.

The assignment guidelines don't state how it should be done, just simply says that the users should be able to log into the site using the details they entered in the register form.

Share this post


Link to post
Share on other sites
  • 0
Ryan2g    0

Alright, good news. I got that to work.

But now, I have another question.

I have session_start(), at the top of the php page, but would it make sense to put it after a successful login? Or always at the top?

Also, as for log out functionality I heard I have to use session_destroy(), how and where would I need to put this?

Share this post


Link to post
Share on other sites
  • 0
Ryan2g    0

Ok, I've fixed the top part. But theres a problem I've noticed.

My code only works for the first set of account details in the users.txt, but if another person was to register and add their information in that users.txt, my code would not let them log in, because it's not reading any other lines, other than the first one.

Anyone have an ideas?

Share this post


Link to post
Share on other sites
  • 0
Ryan2g    0

Well I can't edit my post, but here is the code:

if (isset($_POST["login"])) {
		if ($_POST["username"] != "" && $_POST["password"] != "") {

			// open users.txt for reading
			$file = fopen("users.txt", "r");

			while (!feof($file)) {


					$data = explode (":", fgets($file));

					if ($data[1] == $_POST["username"] && $data[2] == $_POST["password"]) {

						$login = true;
						$_SESSION["login"] = $login;
						$_SESSION["username"] = $_POST["username"];

						//$_SESSION['type'] = $data[3];
						echo "Thank you for logging in, in 5 seconds you will be taken to the homepage.";
						echo "<br>";
						echo '<br>If you do not wish to wait, <a href="home.php">Click Here</a>';
						header("refresh: 5; home.php");
					}
					else {
						$login = false;
						echo "Incorrect login.";
						echo "<br>Your username should be your First Name.";
						echo "<br>Your password should be your Email.";
						echo "<br>";
						echo '<br>Or perhaps you havent registered yet? <a href="register.php">Register Here</a>';
					}
				}
				break;
			}
			fclose($file);
		}
		else {
			$login = false;
			echo "Incorrect login.";
			echo "<br>Your username should be your First Name.";
			echo "<br>Your password should be your Email.";
			echo "<br>";
			echo '<br>Or perhaps you havent registered yet? <a href="register.php">Register Here</a>';
		}
	}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.