• 0

[PHP] Login using data from a text file


Question

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?

15 answers to this question

Recommended Posts

  • 0

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
  • 0

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

  • 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.

  • 0

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;
}
?>

  • 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?

  • 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?

  • 0

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

  • 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.

  • 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?

  • 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?

  • 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</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</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</a>';
		}
	}

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I agree, if Intel wants to make those 50% margins, they really should stick to sockets longer, someone is more likely to upgrade their CPU when they don't need to purchase a motherboard, then looking at maybe RAM, might as well buy a whole new PC at that point, then before you know they've talked themselves out of the whole thing.
    • not sure why people care about the developers so much. let them do whatever they want. if it succeeds, it can benefit us. if it doesn't, then who cares, your life will go on. i'm glad there are still people who do things without thinking whether the output will be productive to society...
    • this man really knows how to embarass americans! i thought he was platforming on "bringing back respect to america!". really sad to see the grip he has over working class americans. he could (and i might argue already has) spit on the working class and half would kiss his shoe. at least this you gotta give him credit for. who else can do this with applause and cheer.
    • Get this 27-inch ASUS VA279QG 120Hz monitor for dirt-cheap by Taras Buria If you are on a very tight budget but you still want to upgrade your monitor to something more exciting than a standard 60Hz office monitor, ASUS has a perfect deal for you. The VA279QG is currently available for as little as $109, and for this money, you get quite a lot of a monitor. The ASUS VA279QG is a big 27-inch IPS monitor with a classic FullHD resolution and a wide 178-degree viewing angle. It can operate with a refresh rate of 120Hz, which is more than enough for buttery-smooth gaming. And since the monitor is FullHD, you will be able to see high refresh rates in more games since your GPU will have to render fewer pixels at 120Hz. Besides, the monitor supports variable refresh rate (VRR), a feature that can further reduce stutters by dynamically adjusting the refresh rate to your FPS. Other display specs include a 1ms MPRT response time, 16.7 million colors, 99% sRGB coverage, and a typical brightness of 300 nits. It is also covered with an anti-glare coating to reduce reflections. Ports-wise, you get one DisplayPort 1.2, one HDMI 1.4, one VGA, and one headphone jack. There are also two 2W speakers, but set your expectation right—these are unlikely to blow your mind with high-quality audio. Finally, there is a VESA 100 mount and a cutout in the base, which lets you mount your phone, namecard, or other small items for extra convenience. 27-inch ASUS VA279QG 120Hz IPS Gaming Monitor - $109 | 22% off on Amazon US This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • lol See... one is only 100% when it's by itself. I live for exceptions to the rule... our talk point was in reference in comparing Vista (not SP1/2) release vs. 7. Any OS will run stable once enough work has been put into it... hell, even Windows 95 had six versions before she was finally complete(d)... just about, what, six or seven months before 98 became available?
  • Recent Achievements

    • Explorer
      treker_ed went up a rank
      Explorer
    • Apprentice
      CHUNWEI went up a rank
      Apprentice
    • Veteran
      1337ish went up a rank
      Veteran
    • Rookie
      john.al went up a rank
      Rookie
    • Week One Done
      patrickft456 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      652
    2. 2
      ATLien_0
      269
    3. 3
      +FloatingFatMan
      176
    4. 4
      Michael Scrip
      155
    5. 5
      Steven P.
      136
  • Tell a friend

    Love Neowin? Tell a friend!