• 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

    • 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?
    • 3uTools 3.26.007 by Razvan Serea 3uTools is a powerful iOS management tool that allows users to efficiently handle their iPhone or iPad without relying on iTunes. It offers seamless data transfer, one-click backup and restore, firmware updates, and a built-in file explorer for easy access to system files. Users can also manage apps, contacts, and media, including photos, videos, and ringtones, all within a simple and intuitive interface. For optimization and maintenance, 3uTools provides battery health monitoring, real-time device information, and system cleanup tools. It also includes features like screen recording, video conversion, and iCloud backup management, making it an essential tool for iOS users looking for greater control over their devices. Key features of 3uTools: iOS device management App installation and removal Firmware downloads and updates Backup and restore functions Data transfer between iOS and PC Ringtone creation Custom wallpaper management Device flashing File system explorer Battery health monitoring Screen capture and recording Video and photo management iCloud backup support Flashing and restoring iOS without data loss 3uTools 3.26.007 changelog: Easy Flash supports iOS 26.0 flashing. Optimized Virtual Location. Fixed some known bugs. Download: 3uTools 3.26.007 | 186.0 MB (Freeware) Download: 3uTools 32-bit | 192.0 MB View: 3uTools Home Page | macOS | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • The development time of this Operating System will have competition with the development time of Star Citizen 😂
    • I saw the 300 in the image and thought it was the number of cores! 🤣
    • Threads is getting a feature Reddit has had for nearly a decade by David Uzondu Back in January, reverse engineer Alessandro Paluzzi (@alex193a) first uncovered that Threads was working on spoiler tags. Now, Meta CEO Mark Zuckerberg (@zuck) has made it official: the feature is in testing. It is a straightforward tool for hiding content, especially text, behind a block that you have to click to reveal, perfect for discussing the ending of your favorite show without ruining the experience for others. It is also, notably, a feature that Reddit has had since January 2017. https://www.threads.com/@zuck/post/DK-BydcJHkF For a platform aiming to be a town square for public discourse, not having a native way to handle spoilers is a small but noticeable handicap for communities focused on pop culture. In a press release, Meta told TechCrunch that popular shows like The Last of Us trended heavily on the app, which the company frames as a sign of a "growing community of entertainment and pop culture enthusiasts." The new feature also supports images so that you can hide shocking visuals or text-filled screenshots. From the images Meta shared, it seems to work just as Paluzzi uncovered months ago. Users with access to the test can highlight text in the composer, and a "mark spoiler" option will appear in a small menu. This method is purely button-based, unlike on Reddit, where users have the option of either using a similar editor button or manually typing out the markdown command >!like this!< to hide their text. This update does not exist in a vacuum. After several months of feeling incomplete, the platform has been getting features that users have actually been asking for. We have seen this with the recent DMs feature, also in testing, which finally gives people a way to have private chats without jumping over to other platforms like Instagram.
  • 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
      659
    2. 2
      ATLien_0
      271
    3. 3
      +FloatingFatMan
      176
    4. 4
      Michael Scrip
      157
    5. 5
      Steven P.
      136
  • Tell a friend

    Love Neowin? Tell a friend!