Solved

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

Posted on 2003-12-11
20
416 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 1

Author Comment

by:FirstBorn
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
so did you try it in that format i had? :p

loz
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 1

Author Comment

by:FirstBorn
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
glad to help

loz
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
These days socially coordinated efforts have turned into a critical requirement for enterprises.
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.

744 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

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now