PDA

View Full Version : [Tut] Simple Multi User Login



Mentor
01-08-2006, 04:27 PM
This tutorial basically shows how to create a Super simple multiple user login.

The tutorial use's a flat file to store user names and passwords, and can be used to protect certain pages, so that only people with user names and passwords can view it. The script created will not be particularly secure so its not a good idea if you need protect something important and is only intended as a basis which you can build on.

Part 1 - The Code
Well the first step is to create the login form and the script which will handle the login.

In this tutorial we will call this login.php Create this fill and add this code.


<?php
if ($_SERVER['REQUEST_METHOD']=="POST"){

// Get UserNames and Passwords.
$Logi = file("users/log.txt");
// Work out how many there are
$size = sizeof($Logi);
// Break appart passwords and usernames
foreach($Logi as $Key => $Val)
{ $Data[$Key] = explode("||", $Val); }
// run threw list and see if any match
for($K = 0; $K<$size; $K++)
{
$user = $Data[$K][0];
$pass = $Data[$K][1];
// If match set cookie and redirect.
if ($user == trim(addslashes($_POST["user"])) && $pass == trim(addslashes($_POST["pass"])) )
{
setcookie("in", 1, time()+3600);
// Start hidden page
header("Location: http://website.com/hidden.php");
}
}
echo "Login Failed.";

// If you didnt log in show login form
} else { ?>
<div style="width:250px">
<div><strong>Simple Login</strong></div>
<div><form name="Login" method="post" action="<?=$_SERVER['PHP_SELF'];?>">
Username:
<input name="user" type="text" >
<br>
Password:
<input name="pass" type="password" >
<br>
<input type="submit" name="Submit" value="Submit">
</form>
</div></div>
<?php
}
?>

The above handles all the logging in as well as the login form. When a user successfully logs in the cookie in is set and they are redirected to the first protected page. Replace http://website.com/hidden.php with your protected page's location.

To work the script requires the user names and passwords.
Create a directory called users
In this create two files.

log.txt


admin||password||
test||pass||
john||pie||

Log.txt stores the user names and passwords in this structure.
Username||Password||

.htaccess

order allow,deny
deny from all
This .htaccess file makes the script more secure by stopping people from viewing the files. Without this people could just navigate to log.txt and read the names and passwords straight off.

The next step is to create the file we want to make secure.
For this example we will use hid.php

<?php
if($_COOKIE['in'] == "1"){}
else{
die("You are not authrised to view this page.");
}
?>
The Meaning of life is... CAKE
This script checks to see if the cookie in exists and if it does not stops the rest of the page from loading and shows the not authorised message.
This script can be used on as many pages as you like to protect what ever content you like, as long as its in a php file.


Part 2 - The Breakdown
Ok in this part of the tutorial i will actually example what's going on.

The First and most complex file is login.php. Although it looks complex what's happening ins actually pretty simple.


<?php
if ($_SERVER['REQUEST_METHOD']=="POST"){
First of all we open php. Then check to see if the Request method is post. Normally the Method is get, except when submitted from a form.
If the method is post, we then fun threw the next bit, if its not we skip to the end and just display the login form



// Get UserNames and Passwords.
$Logi = file("users/log.txt");
// Work out how many there are
$size = sizeof($Logi);

In the above we open the file log.txt using the file function, which creates an array using the different lines. We then work out how many lines there are which is stored the in size variable.



// Break appart passwords and usernames
foreach($Logi as $Key => $Val)
{ $Data[$Key] = explode("||", $Val); }
// run threw list and see if any match

We then want to split up the result further to get both the user name and the password separately. The above takes each part of the array we created and splits that in to two smaller parts, one for the username and one for the password.



for($K = 0; $K<$size; $K++)
{
$user = $Data[$K][0];
$pass = $Data[$K][1];
// If match set cookie and redirect.
if ($user == trim(addslashes($_POST["user"])) && $pass == trim(addslashes($_POST["pass"])) )
{
setcookie("in", 1, time()+3600);
// Start hidden page
header("Location: http://website.com/hidden.php");
}
}
echo "Login Failed.";

This is the part that actually does the work. It looks threw the sets of user names and passwords. If a username and password set match what the user logged in with, the script will set the cookie in, and redirect to the secret page.
http://website.com/hidden.php needs to be changed to that page.
The cookie is set to last one hour although this can be changed by editing the time()+3600 which is how long the cookie will last in seconds.

If none of the passwords match the user will not be redirected and instead see the "login failed" message.



// If you didnt log in show login form
} else { ?>
<div style="width:250px">
<div><strong>Simple Login</strong></div>
<div><form name="Login" method="post" action="<?=$_SERVER['PHP_SELF'];?>">
Username:
<input name="user" type="text" >
<br>
Password:
<input name="pass" type="password" >
<br>
<input type="submit" name="Submit" value="Submit">
</form>
</div></div>
<?php
}
?>
The last part of the script is quite simple, If the request method was not post, it will fall back to the else at the top. Which will then end php and output the login form. Before opening php again to close the brackets for the else.

<?=$_SERVER['PHP_SELF'];?> is used to get the files own location, <?=$var?> is a quick way of opening php to output data.


The Next php file is much simpler


<?php
if($_COOKIE['in'] == "1"){}
else{
die("You are not authrised to view this page.");
}
?>
This is placed at the top of the page you want protected. It then checks to see if the user has the in cookie to say they are logged in. if they do not the page is stopped from loading at that point and the message "You are not authrised to view this page." is displayed.
This can be used on as many pages as you wish to hide what ever content you like.


The .htaccess file and the log.txt were all explained in part one and do not need any further breakdown.



Part 3 - The Extras
This is just to cover the parts missed out of the prior two sections.

Logout.


<?php
setcookie("in", 0, time()-3600);
echo "You are logged out";
?>
This is just a simple script to log a user out, it works by setting the cookies expire date in to the past so it is removed by the browser. It then writes the message "You are logged out" to make sure the user knows what happened.

Flaws.
The main weakness to this method of pass wording is that it users a single cookie to remember whether you are logged in or not.
Because of this it would be quite easy for anyone whom wanted to gain access badly enough to simply forge the cookie.

Note.
This is NOT a user system, simply as pass wording method.

You have to manually add user names and passwords to the log file in this example, Passwords are NOT encrypted. The file is protected via the .htaccess file placed there.

Usernames and passwords must be stored as
Username||password||
The || at the end of password is required so the script doesn't include a newline as part of the users password.

Correctable (Forum Moderator) - Thread moved to Website Tutorials. Nice Tut :D

The Voice
01-08-2006, 05:07 PM
Wow, that's very good. +rep. Very usefull, I've been looking latley for something like that. I will get straight to work on coding it for my site.

Splinter
01-08-2006, 05:46 PM
yep nice tut etc but I would advise people to store the passwords encrypted otherwise the login could be infiltrated..

Mentor
01-08-2006, 06:08 PM
Not realy an issue with this script since the passwords file is htaccess secured so can only be read server side, since the scripts admin has to manualy add and update the usernames and passwords they would have to know them anyway so theres no real problem.
Encriptions realy only nessary if you created a sign up system and allowed new members to register with there own passwords which they would most likly want to remain secure even from that sites administrator "/
But for the purposes of the simple script its unnecessary. The main flaw with this script is the one coverd at the ended with the easly forgeable cookie.

Splinter
01-08-2006, 06:21 PM
Sorry just glanced over the tut and missed the .htaccess script :) nice.

Catchetat
03-08-2006, 11:33 AM
Lovely stuff! +REP

NightSlayer
03-08-2006, 12:56 PM
yeah i like that :D :eusa_danc :eusa_clap :eusa_danc

help23
15-10-2006, 10:31 AM
wow thats realy helpfull welldone plus rep

Verrou
31-10-2006, 05:04 AM
Argh i tried making it on freewebs and i got:
.htaccess contains prohibited characters (.)

so i can't make it cuz it has a . there >.>

Ver.

Mentor
03-11-2006, 06:47 PM
Freewebs also doesnt support php so it wouldnt have worked anyway "/

Firehorse
27-04-2007, 09:38 AM
Argh i tried making it on freewebs and i got:
.htaccess contains prohibited characters (.)

so i can't make it cuz it has a . there >.>

Ver.

Freewebs isn't a proper web host, it's like piczo. Just a small company that lets people easily post things on the net.

Most scripts will not work on Freewebs so it's best to get a proper server,

I was on freewebs for two years and found it horrible, now i use a proper host I can do alot more and even password protect pages without having to pay extra like on Freewebs.

If I were you I would dump freewebs now and get cpanel hosting!

QuickScriptz
28-04-2007, 03:11 AM
Very nice :) +Rep

But did I just miss this part or does the cookie not actually contain any info - meaning that someone could just set the cookie called "in" and be allowed access?

Ini
28-04-2007, 11:24 AM
It looks familiar.

I think ive seen something like this somewhere before.

Nice script ;)

VPSwow
28-04-2007, 11:40 AM
Very nice tut well done :D +rep

Mr.OSH
28-04-2007, 12:08 PM
Another fantastic tutorial Carl. Well Done + rep. I'm sure this could come in handy for me at some point. :D

Invent
28-04-2007, 01:03 PM
But did I just miss this part or does the cookie not actually contain any info - meaning that someone could just set the cookie called "in" and be allowed access?

The cookie "in" has the value of "1".

QuickScriptz
29-04-2007, 03:19 AM
The cookie "in" has the value of "1".

Ya but still... can't I just set a cookie with the value "1" and be let it?

Mentor
29-04-2007, 11:07 PM
Ya but still... can't I just set a cookie with the value "1" and be let it?
Indeed that is true, i did say that in the flaws section near the bottom. It was designed to be as simple as possible, useing a changing value (hash of password etc) would add quite a bit of complexity in that it would need to be checked every time the page was accessed.

You could easly change the cookies value, or name. That way unless someone had the right password to start with and could login once, or were told by someone the cookie name and value its still relativly secure.

Chippiewill
26-06-2007, 02:52 PM
you ripped this


http://thybag.co.uk/?p=Tutorials&ind=38

Mentor
26-06-2007, 03:24 PM
you ripped this


http://thybag.co.uk/?p=Tutorials&ind=38

*chokes* click the link in my sig and guess which site i own :P

Jõnathan
29-06-2007, 09:29 PM
you ripped this


http://thybag.co.uk/?p=Tutorials&ind=38
You sir are an idiot.
Entor's site is thybag.

Mashi
06-07-2007, 09:54 PM
Very Nice tut though its helped me intergrate it with something else

Flisker
27-07-2007, 12:04 PM
you ripped this


http://thybag.co.uk/?p=Tutorials&ind=38


*chokes* click the link in my sig and guess which site i own :P


You sir are an idiot.
Entor's site is thybag.

Sorry i just PMSL. That was too funny.

Nice Tut =] +Rep =]

L?KE
02-09-2007, 05:28 PM
Good Tut + Rep. :)

Sygon..
09-09-2007, 08:10 PM
Just a few questions / input

Why are you using server vars isnt that register_globals shizl.

And the next is

Users can forge a cookie
Users can go on page to view the thing if not logged in? Didnt check that but assuming

Mentor
10-09-2007, 11:12 PM
Just a few questions / input

Why are you using server vars isnt that register_globals shizl.

And the next is

Users can forge a cookie
Users can go on page to view the thing if not logged in? Didnt check that but assuming
1) because i wrote the tut ages ago
2) thats true, i believe i mentioned it was highly insecure and had a few issues. Its an example script, i wouldn't suggest actually useing it.

Eccentric
11-09-2007, 06:53 PM
he wrote it because he was bored. :) and people wouldnt no the difference between secure and insecure.

!!Nathan!!
28-09-2007, 03:20 PM
Helpful thank =] +REP

Lilian
03-10-2007, 08:58 PM
Helpful Indeed :)

luce
26-10-2007, 09:02 AM
Yer thats awsome ty!

BenHughes
16-07-2008, 02:17 PM
Nice tut.

With aloha,
Ben Hughes.

Tom-Brown
22-07-2008, 07:11 PM
Looks great had a quick scim through, all seems right and is a very good flat file system

Tom-743
27-07-2008, 08:40 PM
As pointed out, if you use cookies they can easily be forged. I would use PHP sessions because they are server side so no one can edid/forge them. So the code for login.php would be;



<?php
session_start()
if ($_SERVER['REQUEST_METHOD']=="POST"){

// Get UserNames and Passwords.
$Logi = file("users/log.txt");
// Work out how many there are
$size = sizeof($Logi);
// Break appart passwords and usernames
foreach($Logi as $Key => $Val)
{ $Data[$Key] = explode("||", $Val); }
// run threw list and see if any match
for($K = 0; $K<$size; $K++)
{
$user = $Data[$K][0];
$pass = $Data[$K][1];
// If match set cookie and redirect.
if ($user == trim(addslashes($_POST["user"])) && $pass == trim(addslashes($_POST["pass"])) )
{
$_SESSION['username'] = addslashes ( $user );
$_SESSION['password'] = addslashes ( md5 ( $pass ) );
// Start hidden page
header("Location: http://website.com/hidden.php");
}
}
echo "Login Failed.";

// If you didnt log in show login form
} else { ?>
<div style="width:250px">
<div><strong>Simple Login</strong></div>
<div><form name="Login" method="post" action="<?=$_SERVER['PHP_SELF'];?>">
Username:
<input name="user" type="text" >
<br>
Password:
<input name="pass" type="password" >
<br>
<input type="submit" name="Submit" value="Submit">
</form>
</div></div>
<?php
}
?>


Then for any pages you want to be protected add this to the top;



<?php
session_start();
if ( !isset ( $_SESSION['username'] ) || !isset ( $_SESSION['username'] ) ) {
die ( "You need to login to view this page" );
}
?>

Excellent1
27-07-2008, 09:24 PM
For pages that only users can view once logged in why not just do.

<?php
session_start();
include 'config.php';
if($logged[id] {
echo 'blah blah blah';
} else {
echo 'You need to log in to view that sir!';
}
}
?>

Invent
27-07-2008, 09:28 PM
Excellent, where is $logged defined? As its not in any part of the tutorial..? Do you know what that code actually does? lol.

Excellent1
27-07-2008, 09:32 PM
Excellent, where is $logged defined? As its not in any part of the tutorial..? Do you know what that code actually does? lol.Edit the file, define it, would be much easier as new people to coding don't usually know how to use sessions.

Invent
27-07-2008, 09:33 PM
But they'd know how to set up MySQL queries, get the results of the query, etc? :S (Which is what I assumed $logged would be - the result of a mysql query).

Excellent1
27-07-2008, 09:36 PM
But they'd know how to set up MySQL queries, get the results of the query, etc? :S (Which is what I assumed $logged would be - the result of a mysql query).For multi user login it would be much easier if they just zapped it from a query as you said.


$logged = mysql_query("SELECT * FROM `members` WHERE `id` = '$_SESSION[id]' AND `password` = '$_SESSION[password]'");
$fetchA = mysql_fetch_array($logged);

Then all they have to do is grab it from a config file and use $logged[id] and can pretty much use that for everything.

Invent
27-07-2008, 10:37 PM
But this tutorial is all about flat-files and the code you posted would use $fetchA not $logged for the if statement in your previous post -.-

iTech
27-07-2008, 10:54 PM
But this tutorial is all about flat-files and the code you posted would use $fetchA not $logged for the if statement in your previous post -.-

You're such a great mod! (assisting)
Bumping a 2 year old thread.

Invent
27-07-2008, 10:56 PM
Actually, this isn't classed as bumping as it's in this forum.
Nice try!

Oh and what do you mean by "(assisting)" o_o.

iTech
28-07-2008, 08:53 AM
Actually, this isn't classed as bumping as it's in this forum.
Nice try!

Oh and what do you mean by "(assisting)" o_o.

I thought you'd try to act smart by saying "it's not just me"
Assisting to bump.

Oh and when -repping leave your name, if your not too cowardice.

Invent
28-07-2008, 04:31 PM
I thought you'd try to act smart by saying "it's not just me"
Assisting to bump.Ah, I get 'ya now :)


Oh and when -repping leave your name, if your not too cowardice.I thought it would be obvious that I -repped you as the message was exactly the same as my post.

But anyways! Lets get back on topic :)

Excellent1
28-07-2008, 09:21 PM
Invent - yeah, it was late :P I don't see the point in using a flat file for that when it can be easily done the way I pointed out.

Want to hide these adverts? Register an account for free!