Jump to content

Reading from file (.txt)


NoUser2U

Recommended Posts

Hi,I have a 'register' system where userinfo (first and lastname) is stored in a .txt file (it's just for practice to learn .php better). Now i'm trying to create the login part, where user inputted data is compared with the values stored in the .txt file, and if there is a comparison, then the user 'log's in' successfully.The register part is working, but i don't know how to create the login-part.The .txt file contains the following:Michael;GeorgeJolie;AngelinaPitt;BradNielsen;LeslieNorton;Edward(I couldn't think of something else when testing the register part...:))Now i have the following code:

<?php// LOGIN SCRIPT$txtfile="C:/wamp/www/project_02_login2/files/users.txt";$fh=fopen($txtfile, 'r');// USER ENTERS DETAILS (the form is just for testing, so i kept it as simple as possible)echo "<form method=\"POST\" action=\"\">";echo "Lastname: <input type=\"text\" name=\"lastname\"><br />";;echo "Firstname: <input type=\"text\" name=\"firsttname\"><br />";;echo "<input type=\"submit\" value=\"Submit\">";echo "</form>";$lastname=$_POST['lastname'];	$firsttname=$_POST['firstname'];	// CHECK IF USERINPUT EQUALS A VALUE IN .TXT FILEif(..what to input here?..){	echo "Login successful!";} else {	echo "Login denied";}fclose($fh);?>

Now what do i enter in the if() field?? I need to compare each user-inputted value with the values in the .txt file, which are seperated by a semicolon (; ) and where each line contains 2 (seperated) values. The user can input first and lastname on the login-page, and both values have to equal the 2 values in the file on the same line (For example, userinput 'Brad Jolie' should return no correct match, since it either has to be 'Brad Pitt' or 'Angelina Jolie').Anybody has an idea on how to do this? Thnx in advance

Link to comment
Share on other sites

First, reorganize the document. Put a complete login script at the top of the document, close your PHP tags, and then open a normal HTML document that includes your form. The script itself should be organized so that if the login is successful, a location header redirects the user to another page. If the login fails, the script terminates and the login document is printed again.The easiest way for your script to work is to read the file contents into an array. Then loop through the array elements until you find a match. Sort of like this:

if (isset($_POST['lastname']) && isset($_POST['firstname']) ) { // do nothing if there is no data   $firstname = $_POST['firstname']; // I changed a spelling error here   $lastname = $_POST['lastname'];   $good = false; // initialize flag   $lines = file("path/to/your/file.txt", FILE_IGNORE_NEW_LINES); // returns an array   foreach ($lines as $line) { // loop through each line of the file	  list($first, $last) = explode(';', $line); // split each line at the; character	  if ($firstname == $first && $lastname == $last) {		 $good = true; // it's a match, so set the flag		 break;	  }   }   if ($good) { // the loop terminates with or without a match, so test the flag	  header ('Location: somepage.html');	  exit;   }   // else automatically output the HTML document below}

Note: I wrote this very quickly, and I have not tested it for errors. You should definitely look up every function I've used here that you don't know.

Link to comment
Share on other sites

thnx for your reply! Unfortunately i won't have much time the coming few days due to upcoming exams. As soon as i have time (probably in the coming weekend) i'll try out your suggested method. I'll post by then if i have it working. Fortunately, after giving ur code a quick review, i don't think i'll find much difficulties about understanding the functions. The functions you introduced are functions i have read about in the not so distant past (thnx to the PHP-book), so i think i'll manage to get it working. I'll update this post as soon as i tried it!Thnx again for ur help! :)

Link to comment
Share on other sites

Hi,I have a different example and a few comments/tips regarding your code :)

<?php//default: not logged in$login = false;//check for form submittedif(isset($_POST["firstname"])){	// LOGIN SCRIPT	$lastname=$_POST['lastname'];    	$firsttname=$_POST['firstname'];    	$txtfile="files/users.txt";	//grab all content of the file (just faster in this simple example)	$str_details = file_get_contents($txtfile);	//check for match in file content string	if(strstr($str_details, $lastname) !== false && strstr($str_details, $firstname) !== false)		$login = true;}// USER ENTERS DETAILS (the form is just for testing, so i kept it as simple as possible)if(!$login){	$form = '	<form method="POST" action="">		Lastname: <input type="text" name="lastname"><br />		Firstname: <input type="text" name="firsttname"><br />		<input type="submit" value="Submit">	</form>';		echo $form;}?>

This is a login example where test and form is in the same script. I've based it on your example. Comments:There is a difference between " and ' when using echo: * " allows you to parse variables without concatenating (e.g. echo "My name is $name":) * ' takes everything at face value, however, it allows you to use " inside the string, without escaping it. Look how easily the form was stored in a variable. If I need to add variable to the string I just concatenate the string (e.g. echo 'Hi, my name is '.$name.' and I hereby welcome you, World!'; A small bonus is that linebreaks and indentations as shown in the code are preserved.Relative path vs absolute path:Your file path was an absolute path, meaning you'd need to change it when you upload it to the website. Highly impractical. If you instead use a relative path as shown above it will work both locally and live.Hope you find this helpful :)

Link to comment
Share on other sites

Relative path vs absolute path:Your file path was an absolute path, meaning you'd need to change it when you upload it to the website. Highly impractical. If you instead use a relative path as shown above it will work both locally and live.
i think opening file through absolute path is better as per security..and peroformance...allow_url_fopen is probably should be put off...and using relative path send a request to the file..http://somesite/somepage.php and i guess its little slow process. where as absolute path do the job localy and serve the pages out..and most probably there is a bandwith issue there also..
Link to comment
Share on other sites

I'm not sure about the point about security... if the path doesn't depend on user input, it's irrelevant whether it's absolute or not. And if it is dependant, your best best is to resolve it to an absolute path (by using realpath()), and verifying the location is an accepted one.And as far as performance is concerned... the overhead of resolving a relative path to an absolute one is just as neglectible as the difference between single and double quotes, if not more - not something you really should try to optimize for. The portability payoff is much greather. Here's an example....

Link to comment
Share on other sites

First, reorganize the document. Put a complete login script at the top of the document, close your PHP tags, and then open a normal HTML document that includes your form. The script itself should be organized so that if the login is successful, a location header redirects the user to another page. If the login fails, the script terminates and the login document is printed again.The easiest way for your script to work is to read the file contents into an array. Then loop through the array elements until you find a match. Sort of like this:*CODE*Note: I wrote this very quickly, and I have not tested it for errors. You should definitely look up every function I've used here that you don't know.
Hi again,Over the last couple of days i struggled with the code. I looked up the few things i didn't understand at first, read about 'm and then i understood them. But still i couldn't get the code working. I finally have it working now, because ALL the time i was working without the addition of 'FILE_IGNORE_NEW_LINES' in file()....I read about that optional parameter and the explainment about it made it clear for me...but still i don't understand why it didn't work without it. The code i currently have is this: (it is working now)
<?php$users="C:/wamp/www/project_02_login2/files/users.txt";$fh=fopen($file, 'r');$lines=file($users, FILE_IGNORE_NEW_LINES);if(isset($_POST['firstname']) && isset($_POST['lastname'])){ // This does not work 100%	$firstname=$_POST['firstname'];	$lastname=$_POST['lastname'];		foreach($lines as $line){		list($ln, $fn)=explode(';', $line);		if($lastname==$ln && $firstname==$fn){ // THIS IS WORKING NOW, THNX TO ADDING 'FILE_IGNORE_NEW_LINES' in file()			echo 'Login was successful!';			break;		} else { 			echo 'Login failed!';			break;		}		}} else {	echo 'Please enter your details below';}?><form method="POST" action="">fname: <input type="text" name="firstname"><br />lname: <input type="text" name="lastname"><br /><input type="submit" name="submit" value="Submit!"><br /></form>

Now, the .txt-file contains this:test1b;test1atest2b;test2atest3b;test3atest4b;test4atest5b;test5atest6b;test6atest7b;test7atest8b;test8aMy question about file(..., FILE_IGNORE_NEW_LINES): what does it exactly do? The php-manual says that it does not add new lines at the end of each array element. Now when i look at the above .txt-file......how does 'FILE_IGNORE_NEW_LINES' alter the contents of the file? For example, when i used the following code:

<?php$users="C:/wamp/www/project_02_login2/files/users.txt";$fh=fopen($file, 'r');$lines=file($users); // NO FILE_IGNORE_NEW_LINES addedforeach($lines as $line){		print_r(list($ln, $fn)=explode(';', $line)); // for checking out what the effect is of the absence of FILE_IGNORE_NEW_LINES} ?>

and tested it out in the browser and finally looking at the source, i saw this:Array( [0] => test1b [1] => test1a)Array( [0] => test2b [1] => test2a)etc. etc. until test8b;test8a.Confusingly, I saw the same effect in the source when i added FILE_IGNORE_NEW_LINES to file(). It did make the login-code work though, but i failed to directly see the effect of it in the source in the browser. So what does FILE_IGNORE_NEW_LINES exactly do?What i also don't understand in your method, is why you used 'flags'. For example, you had:

if ($firstname == $first && $lastname == $last) {		 $good = true; // it's a match, so set the flag		 break;}.. // THEN SHORTLY FOLLOWED BY:.if ($good) {	  header ('Location: somepage.html');	  exit;}

But why not simply use?:

if($firstname==$first && $lastname==$last){	  header ('Location: somepage.html');	  exit; // EXITING THE FOREACH-LOOP}

Btw, much thnx for your method Dreidre's dad! :).

Hi,I have a different example and a few comments/tips regarding your code :)*CODE*This is a login example where test and form is in the same script. I've based it on your example. Comments:There is a difference between " and ' when using echo: * " allows you to parse variables without concatenating (e.g. echo "My name is $name":) * ' takes everything at face value, however, it allows you to use " inside the string, without escaping it. Look how easily the form was stored in a variable. If I need to add variable to the string I just concatenate the string (e.g. echo 'Hi, my name is '.$name.' and I hereby welcome you, World!'; A small bonus is that linebreaks and indentations as shown in the code are preserved.Relative path vs absolute path:Your file path was an absolute path, meaning you'd need to change it when you upload it to the website. Highly impractical. If you instead use a relative path as shown above it will work both locally and live.Hope you find this helpful :(
Thank you alot for your contribution Jannik Olsen! I found the way you implemented the form in the php-code a big big helpful thing. I did know about the difference between " and '.....but i had never thought of using it the way you showed for adding the html form code. It will save me a lot of irritation the next time. Thnx!!About your suggested method: i will definately check it out too in the next few days, although Dreidre's dad is working too now. But i'll check yours anyway since it will be helpful in learning the language better and getting familiar with more functions is always a good thing i guess <_<.
Link to comment
Share on other sites

I added the flag because I was in a hurry and was remembering some code I had just written where a flag was important. It is safe to ignore that part. :)A text file like yours has a newline character separating every line. (That's why it looks like lines instead of a huge block of text.) File() uses that character to break the file into segments for the array. The FILE_IGNORE_NEW_LINES constant tells file() whether it should keep the newline character or throw it away. If it keeps it, your password strings will all have a newline character at the end, so they will not match the string passed into your POST array. That is why we throw it away.It's hard to know what effect a newline character might have when you dump the array contents. I wouldn't worry about it.

Link to comment
Share on other sites

That option controls if the newline character is part of the text returned. Without the option, one line would be returned like this:"test1b;test1a\n"With the \n newline character on the end. When you explode it, the second part is "test1a\n", still with the newline at the end. Using the option tells it to return the text on the lines but leave off the newline on the end. It's hard to detect that in debugging because the newline character just adds a "return" to the end of the text, but you don't see it otherwise. If you used var_dump it will tell you the value and also the type (and for strings it quotes the value, so you can see where it ends). So if you add a var_dump here:

foreach($lines as $line){  var_dump($line);

The difference you see in the two options will be something like this:

String(14): "test1b;test1a"

String(13): "test1b;test1a"

Note that the lengths are different, and that the first one has the quote on the next line because of the terminating newline character.You could also get rid of the newline yourself if you used trim on the text:list($ln, $fn)=explode(';', trim($line));

Link to comment
Share on other sites

Amazing! THNX a LOT both of you for explaining that part! If i knew you guys in persons i would just get over there and shake both of you your hands...seriously !! Thank you so much! (btw does this forum have a function to give 'reps' to other users? Because i would gladly like to give you guys reps!')Offtopic:May i ask if you guys followed any course/eduction about programming? Or did you learn it all by selfstudy? I ask this because you seem to know ALOT about php, programming and website-building....and i would like that too :)

Link to comment
Share on other sites

The reputation system isn't enabled here, but I am working on a way for people to buy me beers.I've got a degree in computer science and several years of professional experience with it. I'm not sure about Dad, but I know he's really old so he was probably around when they were inventing all of this stuff.

Link to comment
Share on other sites

You can go to our profile pages and click 1-5 stars. I've got my five, so it won't matter much, but thanks for asking.I started learning web when it was too new for classes to exist, and I've just stuck with that. If 47 is old, I'm old.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...