• 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

    • That's wonderful. A shame that a few fringe nutjobs will somehow concoct a story to make this something nefarious. I do wish he'd committed to using more of the foundation's funds for scientific/medical research here at home, though. It looks like the U.S. is suddenly poised to become a backwoods nation in research.
    • Scientists explain how water could have actually made Mars the red planet it is today by Sayan Sen For centuries, scientists have wondered why Mars is red. The long-standing theory was that the planet’s rusty color came from hematite, an iron-rich mineral formed in dry conditions. But new research suggests something else might be responsible: ferrihydrite, an iron oxide-hydroxide mineral that forms in wet environments. A study published in Nature Communications by researchers from Brown University and the University of Bern suggests that ferrihydrite (Fe5O8H · nH2O) is the dominant iron-containing mineral in Martian dust. Their findings—based on orbital observations, rover data, and lab experiments—challenge previous ideas about Mars' surface composition. “The fundamental question of why Mars is red has been thought of for hundreds if not thousands of years,” said Adomas Valantinas, a postdoctoral fellow at Brown University. “From our analysis, we believe ferrihydrite is everywhere in the dust and also probably in the rock formations, as well.” Ferrihydrite is formed when iron reacts with oxygen and water. On Earth, it’s commonly found in volcanic rock and ash. Its presence on Mars suggests that the planet was once much wetter, with conditions that could have supported liquid water. This contrasts with hematite, which forms in drier environments. To test their theory, the researchers recreated Martian conditions in a lab. They ground minerals into tiny particles—about 1/100th the width of a human hair—matching the size of real Martian dust. They then studied how light reflected off these particles. The results showed that ferrihydrite remains stable in Mars’ current dry, cold climate, but its structure still holds signs that it formed when the planet had water. “What we know from this study is the evidence points to ferrihydrite forming, and for that to happen there must have been conditions where oxygen and water could react with iron,” Valantinas explained. “Those conditions were very different from today’s dry, cold environment.” To confirm ferrihydrite’s presence, the team studied data from NASA’s Mars Reconnaissance Orbiter and ESA’s Mars Express and Trace Gas Orbiter. They also used spectral readings from rovers like Curiosity, Pathfinder, and Opportunity. Combining all of these sources, they found that the mineral appears widespread on the Martian surface. This discovery challenges previous theories that Mars gradually oxidized in dry conditions. Instead, it suggests that ancient Mars went through a wetter phase before drying out. That shift from a water-rich past to the dry, dusty planet we see today is key to understanding Mars’ climate history—and possibly its ability to support life. “The study is a door-opening opportunity,” said Jack Mustard, senior author of the study. “It gives us a better chance to apply principles of mineral formation and conditions to tap back in time.” While the findings provide strong evidence for ferrihydrite’s role in Mars’ red dust, definitive proof will have to wait until Mars samples—currently being collected by NASA’s Perseverance rover—are brought back to Earth. Scientists hope these samples will confirm the theory and shed more light on the planet’s environmental history. Source: Brown University, University of Bren, Nature | Image via Depositphotos This article was generated with some help from AI and reviewed by an editor. Under Section 107 of the Copyright Act 1976, this material is used for the purpose of news reporting. Fair use is a use permitted by copyright statute that might otherwise be infringing.
    • I would say 98% of people you can't figure out how to install Linux would never attempt to install Windows. It's not news non-tech savvy people can't install an PC OS.
    • Do I really have to tell you that people generally don't make random posts about how Windows is running perfectly for them? Of course you're seeing more posts about people hating Windows, it's just a very loud minority as usual.
    • ...and not really appropriate for most people for desktop usage.
  • Recent Achievements

    • Week One Done
      jrromero17 earned a badge
      Week One Done
    • One Month Later
      jrromero17 earned a badge
      One Month Later
    • Conversation Starter
      johnwin1 earned a badge
      Conversation Starter
    • One Month Later
      Marwin earned a badge
      One Month Later
    • One Year In
      fred8615 earned a badge
      One Year In
  • Popular Contributors

    1. 1
      +primortal
      237
    2. 2
      snowy owl
      156
    3. 3
      ATLien_0
      142
    4. 4
      +FloatingFatMan
      132
    5. 5
      Xenon
      131
  • Tell a friend

    Love Neowin? Tell a friend!