• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 430
  • Last Modified:

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

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
FirstBorn
Asked:
FirstBorn
  • 10
  • 10
1 Solution
 
lozlozCommented:
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
 
FirstBornAuthor Commented:
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
 
lozlozCommented:
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
FirstBornAuthor Commented:
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
 
FirstBornAuthor Commented:
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
 
lozlozCommented:
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
 
FirstBornAuthor Commented:
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
 
lozlozCommented:
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
 
FirstBornAuthor Commented:
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
 
lozlozCommented:
so did you try it in that format i had? :p

loz
0
 
FirstBornAuthor Commented:
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
 
lozlozCommented:
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
 
FirstBornAuthor Commented:
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
 
lozlozCommented:
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
 
FirstBornAuthor Commented:
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
 
lozlozCommented:
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
 
FirstBornAuthor Commented:
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
 
lozlozCommented:
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
 
FirstBornAuthor Commented:
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
 
lozlozCommented:
glad to help

loz
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 10
  • 10
Tackle projects and never again get stuck behind a technical roadblock.
Join Now