Solved

Login to Private (members only) site using Text File as Database...

Posted on 2003-12-11
20
423 Views
Last Modified: 2009-07-29
Hi Everyone!

I'm looking to use a text file as a database to log in to a password protected site.

The Text File looks like this:
--------info.txt----------
[1]firstusername,firstpassword
[2]secondusername,secondpassword
[3]thirdusername,thirdpassword
--------etc.---------------
(the format can be changed, as long as I can add multiple

usernames with respective passwords.)

So Far, the .php files that I have are listed below.

I'm still a newbie to php, so please be descriptive (as in,

please provide code, not just needed procedure)

Thanks In Advance!

:)

FirstBorn
------------------------------------
index.php
------------------------------------
<HTML>
<BODY>
<P Align=Center>Welcome.</P>
<BR>
<P Align=Center>Please Log In</P>
<BR>
<form action="login.php" method="post">
<Center>
<div><B>User Name:</B></div>
<input type="text" name="username" size="20" maxlength="100"
value="">
<BR>
<div><B>Password:</B></div>
<input type="text" name="password" size="20" maxlength="100"
value="">

<BR>
<input type="Submit" name="submit" value="Submit">
<input type="Reset">
</Center>
<BR>
</form>
</BODY>
</HTML>
-----------------------------
login.php
-----------------------------
<HTML>
<BODY>
<P Align=Center>First Page After Login</P>
<?php
    session_start(); // Starts an existing session, or creates a new, if no session exists

    // The username and password from the login form
    if (isset($_POST['username']) && isset($_POST['password'])) {
        if($_POST['username'] == 'member' && $_POST['password'] == 'secret') {
            $_SESSION['username'] = $_POST['username'];
        }
    }
    // If the login is successful
    if ( isset ( $_SESSION['username'] ) ) {
        die('<meta http-equiv="refresh" content="0; url=members.php">');
    }
       
?>
</BODY>
</HTML>
-------------------------------
0
Comment
Question by:FirstBorn
  • 10
  • 10
20 Comments
 
LVL 13

Expert Comment

by:lozloz
ID: 9922398
hi there,

using a text file will not be particularly secure unless you store it below the root of the website. also you need session_start() at the very top of pages, before any content. also i put your html at the end so you can use header(); instead of a javascript version

login.php:

<?php session_start(); ?>
    // The username and password from the login form
    if (isset($_POST['username']) && isset($_POST['password'])) {
      $file = file_get_contents("C:\\adirectory\\belowwebserverroot\\users123123.txt"); // you need to change this to be the location of your text file - not accessible from the web for security if possible. double backslash cos it needs to be escaped (only backslash on windows)
      $data = explode("\n", $file); // split it apart by line breaks
      foreach($data as $val) {
        $line[] = explode(",", $val); // split the lines by commas - therefore no commas can be allowed in the usernames or passwords
      }
      $num = count($line);
      for($x = 0; $x < $num; $x++) {
        $username = trim($line[0]); // var holding first half of a line (username)
        $password = trim($line[1]); // var holding second half of a line (password)
        if(trim($_POST['username']) == $username && trim($_POST['password']) == $password) { // if the 2 fields match a line
          $_SESSION['username'] = $_POST['username']; // register the session
        }
      }
    } else {
      die("No username or password input");  // exit because no information was sent
    }
    // If the login is successful
    if ( isset ( $_SESSION['username'] ) ) {
      header("Location: members.php"); // go to members.php
      exit;
    }
// otherwise login failed and continue below
?>
<HTML>
<BODY>
<P Align=Center>Login failed</P>
</BODY>
</HTML>

think that should work.. if it doesn't gimme a message and if you don't understand anything then i'll try to explain it

loz
0
 
LVL 1

Author Comment

by:FirstBorn
ID: 9922920
Hi loz!

It's a pleasure seein' ya around again!

k... I have the info.txt set up as above,  Added the code to the login.php page,

had to take off the ?> part off of the script here: <?php session_start(); ?>

(I think it was cancelling out the script.)

I am using the temporary location of $file = file_get_contents("info.txt");

I've attempted using a correct username, password, but get 'login failed'

I've attempted to submit empty username and password fields,

Still get 'login failed' instead of getting "No username or password input"

Thanks...

:)

FirstBorn


0
 
LVL 13

Expert Comment

by:lozloz
ID: 9923200
i guess i shoulda tested it then

<?php session_start();
    // The username and password from the login form
    if (isset($_POST['username']) && isset($_POST['password'])) {
      $file = file_get_contents("C:\\adirectory\\belowwebserverroot\\users123123.txt"); // you need to change this to be the location of your text file - not accessible from the web for security if possible. double backslash cos it needs to be escaped (only backslash on windows)
      $data = explode("\n", $file); // split it apart by line breaks
      foreach($data as $val) {
        $line[] = explode(",", $val); // split the lines by commas - therefore no commas can be allowed in the usernames or passwords
      }
      $num = count($line);
      for($x = 0; $x < $num; $x++) {
        $username = trim($line[$x][0]); // var holding first half of a line (username)
        $password = trim($line[$x][1]); // var holding second half of a line (password)
        $userfile = trim($_POST["username"]);
        $passfile = trim($_POST["password"]);
        print ($userfile == $username);
        print ($passfile == $password);
        if($userfile == $username AND $passfile == $password) { // if the 2 fields match a line
          $_SESSION["username"] = $password; // register the session
        }
      }
    } else {
      die("No username or password input");  // exit because no information was sent
    }
    // If the login is successful
    if ($_SESSION["username"]) {
      header("Location: members.php"); // go to members.php
      exit;
    }
// otherwise login failed and continue below
?>
<HTML>
<BODY>
<P Align=Center>Login failed</P>
</BODY>
</HTML>

that should work (tested it this time), tell me if it doesn't and i'll try and patch it up

cheers,

loz
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
LVL 1

Author Comment

by:FirstBorn
ID: 9923328
Hi loz,

Nope... No go...

Just a reminder, I have the info.txt file in the same directory as this script.  

I know that you said for security reasons that I need to change the file location,

but It's on my webserver from my webhost, not from home.  

I'll probably just CHMOD the info.txt file differently after testing.

Thanks...

:)

FirstBorn
0
 
LVL 1

Author Comment

by:FirstBorn
ID: 9923340
Hi loz,

Ooops...

Here's the code I'm using.

Thanks...

:)

FirstBorn



<?php session_start();
    // The username and password from the login form
    if (isset($_POST['username']) && isset($_POST['password'])) {
      //$file = file_get_contents("C:\\adirectory\\belowwebserverroot\\users123123.txt"); // you need to change this to be the location of your text file - not accessible from the web for security if possible. double backslash cos it needs to be escaped (only backslash on windows)
      $file = file_get_contents("info.txt");
      $data = explode("\n", $file); // split it apart by line breaks
      foreach($data as $val) {
        $line[] = explode(",", $val); // split the lines by commas - therefore no commas can be allowed in the usernames or passwords
      }
      $num = count($line);
      for($x = 0; $x < $num; $x++) {
        $username = trim($line[$x][0]); // var holding first half of a line (username)
        $password = trim($line[$x][1]); // var holding second half of a line (password)
        $userfile = trim($_POST["username"]);
        $passfile = trim($_POST["password"]);
        print ($userfile == $username);
        print ($passfile == $password);
        if($userfile == $username AND $passfile == $password) { // if the 2 fields match a line
          $_SESSION["username"] = $password; // register the session
        }
      }
    } else {
      die("No username or password input");  // exit because no information was sent
    }
    // If the login is successful
    if ($_SESSION["username"]) {
      header("Location: members.php"); // go to members.php
      exit;
    }
// otherwise login failed and continue below
?>
<HTML>
<BODY>
<P Align=Center>Login failed</P>
</BODY>
</HTML>
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9923358
you changed $file = file_get_contents("C:\\adirectory\\belowwebserverroot\\users123123.txt"); to

$file = file_get_contents("info.txt"); ?

if so what about it doesn't work? can i see your info.txt file (if its a test one)

loz
0
 
LVL 1

Author Comment

by:FirstBorn
ID: 9923435
Hi loz,

"can i see your info.txt file (if its a test one)"

Yep, Exactly As listed above: (without the "-----------",  I'm using that as a divider)

---------------------------------------
[1]firstusername,firstpassword
[2]secondusername,secondpassword
[3]thirdusername,thirdpassword
---------------------------------------

Thanks...

:)

FirstBorn
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9923671
what doesn't work about it?

can you remove the [1] [2] [3], or do you need them as id's, in my system i just had

username,password
user2,pass2

loz
0
 
LVL 1

Author Comment

by:FirstBorn
ID: 9924332
Hi loz,

Sure... As I wrote in the original part of this Q:

"(the format can be changed, as long as I can add multiple

usernames with respective passwords.)"

Thanks...

:)

FirstBorn
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9924925
so did you try it in that format i had? :p

loz
0
 
LVL 1

Author Comment

by:FirstBorn
ID: 9925056
Hi loz,

I apologize... I was in the midst of running around here like a chicken with it's head cut off...

k... I changed the format to:
username,password

I clicked Submit after entering the pertinent information and get this error:

"11
Warning: Cannot modify header information - headers already sent by (output started at /home/path/to/login.php:16) in /home/path/to/login.php on line 27"

Thanks...

:)

FirstBorn
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9925065
whoops left some debugging in there - if you want to test again with incorrect data you can actually use this to make sure that the system works properly

first enter an incorrect username and an incorrect password. the result should be 10. then try correct username and incorrect password, hopefully resulting in 01. if this is correct, remove these lines:

        print ($userfile == $username);
        print ($passfile == $password);

and it'll work hopefully. just careful about the session still being present when testing the script multiple times

loz
0
 
LVL 1

Author Comment

by:FirstBorn
ID: 9925103
Hi loz,

k... I entered in the correct user/pass and get the same error as above,

I entered nothing (left the user and password text input boxes blank) and it works,

I entered a wrong user/pass and it works...

I think that the code maybe backwards... ;P

Thanks...

:)

FirstBorn
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9925152
how do you mean it works? do you mean it redirects you to the correct page? if so this is probably because the session is still registered as i said, you need to get rid of the session by doing unset($_SESSION["username"]); somewhere.. that's pretty much what i expected except for the blank username/password one - you need to make sure that sessions are not present. when i was testing i took out the session register and just got the script to die at that point with a message saying that the form username was the same as the text one

im pooped so i gotta catch some sleep but leave a message if you're still having trouble

loz
0
 
LVL 1

Author Comment

by:FirstBorn
ID: 9925412
Hi loz,

Adding "unset($_SESSION["username"]);" in the script worked.

(I'll post the modified code below.)

Just one more thing.  How do I create a log out using a link with

the "unset($_SESSION["username"]);" code and have the user brought

back to the Main Page?

Thanks for All of Your Help and Hope you have gotten Plenty of Rest by the time You read this... :)

Thanks...

:)

FirstBorn
-------------------------------------
<?php session_start();
    // The username and password from the login form
    if (isset($_POST['username']) && isset($_POST['password'])) {
      //$file = file_get_contents("C:\\adirectory\\belowwebserverroot\\users123123.txt"); // you need to change this to be the location of your text file - not accessible from the web for security if possible. double backslash cos it needs to be escaped (only backslash on windows)
      $file = file_get_contents("info.txt");
      $data = explode("\n", $file); // split it apart by line breaks
      foreach($data as $val) {
        $line[] = explode(",", $val); // split the lines by commas - therefore no commas can be allowed in the usernames or passwords
      }
      $num = count($line);
      for($x = 0; $x < $num; $x++) {
        $username = trim($line[$x][0]); // var holding first half of a line (username)
        $password = trim($line[$x][1]); // var holding second half of a line (password)
        $userfile = trim($_POST["username"]);
        $passfile = trim($_POST["password"]);
        //print ($userfile == $username);
        //print ($passfile == $password);
        if($userfile == $username AND $passfile == $password) { // if the 2 fields match a line
          $_SESSION["username"] = $password; // register the session
        }
      }
    } else {
      die("No username or password input");
      unset($_SESSION["username"]);  // exit because no information was sent
    }
    // If the login is successful
    if ($_SESSION["username"]) {
      header("Location: members.php"); // go to members.php
      exit;
    }
// otherwise login failed and continue below
?>
<HTML>
<BODY>
<P Align=Center>Login failed</P>
</BODY>
</HTML>
----------------------------------
0
 
LVL 13

Accepted Solution

by:
lozloz earned 500 total points
ID: 9927787
in your body..

<a href="logout.php">

logout.php:

<?
session_start();
$_SESSION = array(); // session now contains an empty array
header("Location: index.php"); // redirect to index.php
exit;
?>

cheers,

loz
0
 
LVL 1

Author Comment

by:FirstBorn
ID: 9928056
Hi loz,

I'm on my way out for a little while, but I noticed one problem.

I can Still view the page even if I don't log in.

For Example:

I Don't want the user to type in something like:

http://www.mysite.com/members/members.php

and view the file.  I Need it so that they HAVE to Log In to View it,

Else, they can't view it.

Is there code to not view the file unless they log in?

Thanks...

:)

FirstBorn
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9928141
at the top of members.php..

<?php
session_start();
if(!$_SESSION["username"]){ // not logged in
  die("You must be logged in to view this page");
}

loz
0
 
LVL 1

Author Comment

by:FirstBorn
ID: 9929711
Hi loz,

Thank You, Again, VERY Much!!!

You're a GENIUS!

Everything is the way I want it to be, Thanks to You.

:)

Christopher
0
 
LVL 13

Expert Comment

by:lozloz
ID: 9929775
glad to help

loz
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question