• 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

    • OBS Studio 31.1.0 RC1 by Razvan Serea OBS Studio is software designed for capturing, compositing, encoding, recording, and streaming video content, efficiently. It is the re-write of the widely used Open Broadcaster Software, to allow even more features and multi-platform support. OBS Studio supports multiple sources, including media files, games, web pages, application windows, webcams, your desktop, microphone and more. OBS Studio Features: High performance real time video/audio capturing and mixing, with unlimited scenes you can switch between seamlessly via custom transitions. Live streaming to Twitch, YouTube, Periscope, Mixer, GoodGame, DailyMotion, Hitbox, VK and any other RTMP server Filters for video sources such as image masking, color correction, chroma/color keying, and more. x264, H.264 and AAC for your live streams and video recordings Intel Quick Sync Video (QSV) and NVIDIA NVENC support Intuitive audio mixer with per-source filters such as noise gate, noise suppression, and gain. Take full control with VST plugin support. GPU-based game capture for high performance game streaming Unlimited number of scenes and sources Number of different and customizable transitions for when you switch between scenes Hotkeys for almost any action such as start or stop your stream or recording, push-to-talk, fast mute of any audio source, show or hide any video source, switch between scenes,and much more Live preview of any changes on your scenes and sources using Studio Mode before pushing them to your stream where your viewers will see those changes DirectShow capture device support (webcams, capture cards, etc) Powerful and easy to use configuration options. Add new Sources, duplicate existing ones, and adjust their properties effortlessly. Streamlined Settings panel for quickly configuring your broadcasts and recordings. Switch between different profiles with ease. Light and dark themes available to fit your environment. …and many other features. For free. At all. OBS Studio 31.1.0 RC1 changelog: Fixed an issue where a Browser Source or Browser Dock would crash OBS Studio on macOS 13 or older [jcm93/PatTheMav/RytoEX] Fixed an issue where browser error pages could not scroll [WizardCM] Fixed an issue on macOS where menu items would launch unintended actions when OBS was set to certain languages [gxalpha] Fixed an issue in Beta 1-2 where the group icon in the Sources list was not positioned correctly in the System theme [shiina424] Fixed an issue in Beta 2 where the preview zoom button tooltip translations were incorrect [shiina424] Download: OBS Studio 31.1.0 RC1 | Portable | ARM64 | ~200.0 MB (Open Source) View: OBS Studio Homepage | Other Operating Systems | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Nice little improvement One improvement I would like to see. Being able to use a voice commands in Firefox "Firefox, 2FA (enter a 2FA code)". "Firefox, Close all tabs right" "Firefox, Pin tab" "Firefox, Bookmarks (name of Bookmark to open a Bookmark)" "Firefox, Settings, X" among others.
    • Microsoft Defender XDR gets TITAN-powered Security Copilot recommendations by Paul Hill Guided Response, a Copilot-powered capability in Microsoft Defender XDR that guides analysts through step-by-step investigation and response flows, is getting a big upgrade with the introduction of TITAN recommendations. With TITAN, Microsoft wants to give security analysts real-time, threat-intel-driven recommendations so they can better prepare against attacks, before they even happen. TITAN is an adaptive threat intelligence graph that uses data from first and third-party telemetry and employs guilt-by-association techniques to warn analysts about unknown IP addresses that could pose a threat, due to their association with known malicious addresses. The primary benefit of TITAN is that security analysts get faster warnings about potential threats before they even have a chance to cause a problem. TITAN is an enhancement of Security Copilot Guided Response, rather than a replacement to it. With this extra tool, security analysts will be able to better keep up with evolving threats. Understanding TITAN's AI-powered threat intelligence The Redmond giant said that TITAN “represents a new wave of innovation” built upon its threat intelligence capabilities that introduces a real-time, adaptive threat intelligence graph. It takes telemetry from first and third-party sources such as Microsoft Defender for Threat Intelligence, Microsoft Defender for Experts, and customer feedback. The graph uses guilt-by-association techniques to mark unknown devices as threats, if they’re associated with known malicious entities. This gives security analysts a window of opportunity to take action and prevent harm. To identify potential threats, Microsoft uses a semi-supervised label propagation technique that assigns reputation scores to nodes based on the score of their neighbors. These reputation scores allow Microsoft’s unified security operation platform to implement containment and remediation actions via attack disruption. Practical impact and future outlook The new TITAN suggestion now appears within Guided Response as triage and containment recommendations. When a suspicious IP is detected, a Guided Response recommendation is automatically generated. These can help security analysts deal with various threats including IP addresses, IP ranges, and email senders. Microsoft said in early testing its TITAN recommendations have shown good results. TITAN boosted Guided Response triage accuracy by 8%, it reduced the time needed to investigate and respond to incidents, and its explainable recommendations gave analysts more confidence in the actions they take. As threats become more sophisticated, Microsoft’s TITAN will help to tackle threats before they even become an issue.
    • China wants the tech... if they were to invade, TSMC would destroy it's fabs and other critical information first. Plus, you can bet they have backups stored NOT in Taiwan.
    • Malware website host in China in 3….2…1
  • Recent Achievements

    • Enthusiast
      Motoman26 went up a rank
      Enthusiast
    • Mentor
      M. Murcek went up a rank
      Mentor
    • Explorer
      treker_ed went up a rank
      Explorer
    • Apprentice
      CHUNWEI went up a rank
      Apprentice
    • Veteran
      1337ish went up a rank
      Veteran
  • Popular Contributors

    1. 1
      +primortal
      674
    2. 2
      ATLien_0
      267
    3. 3
      +FloatingFatMan
      176
    4. 4
      Michael Scrip
      174
    5. 5
      Steven P.
      139
  • Tell a friend

    Love Neowin? Tell a friend!