Post by Jacob on Jun 12, 2009 14:39:15 GMT -5
A user authentication system is required for most large webapps. The login script we will make in this tutorial will be flatfile based, and contain login, register, and logout features.
Let’s start with the first and most important file, login.php.
The action is set in the query parameter ‘a’. If the variable is not set, we will show the user a login form.
Next, the register form. In this script, the data is stored in the following format:
etc.
The login section of the file:
The last section in the file logs the user out if they request it.
Next file: global.php. This file is included in the other files of your script and determines if the user is logged in.
We also need a form for the user to register, register.php.
Last, index.php. This file can be replaced with your own code when you use this script.
And you’re done! If you use this, feel free to leave a comment on this post, linking to your site.
Make sure you use a .htaccess file to block access to the data file to prevent stealing of passwords and usernames. You can also store it out of the www root.
Let’s start with the first and most important file, login.php.
The action is set in the query parameter ‘a’. If the variable is not set, we will show the user a login form.
<?php
include("global.php");
$filename = "data/users/data.php";
if(!isset($_GET['a']))
{
?>
<form action="login.php">
<table cellpadding="5" align="center">
<tr>
<td>
Username
</td>
<td>
<input type="text" name="username" />
</td>
<tr>
<td>
Password
</td>
<td>
<input type="password" name="pass" />
</td>
</tr>
<tr>
<td>
Submit
</td>
<td>
<input type="hidden" name="a" value="user_login">
<input type="submit" value="Log In" />
</td>
</tr>
</table>
</form>
<?php
exit();
}
Next, the register form. In this script, the data is stored in the following format:
user | MD5'd password
user2 | MD5'd password
etc.
if($_GET['a'] == "user_register")
{
if($_GET['username'] == '' || $_GET['pass'] == '')
message("You must specify a username and password.");
elseif($_GET['1'] + $_GET['2'] != $_GET['check'])
message('You answered the security question incorrectly.');
$f = fopen($filename, 'r+') or die("Could not open users file.");
@$users = explode("\n", fread($f, filesize($filename))); //Explode the users file into an array of lines
for($i = 0; $i < count($users); $i++)
{
$users[$i] = explode(" | ", $users[$i]); //Explode by the |
}
$user_exists = 0;
for($i = 0; $i < count($users); $i++)
{
if($users[$i][0] == $_GET['username'])
$user_exists = 1; //If the user already exists, set a variable.
}
if($user_exists == 1)
die("The user \"{$_GET['username']}\" already exists."); //Stop if the user exists
$to_add = $_GET['username'].' | '.md5($_GET['pass']);
fwrite($f, "\n".$to_add) or die("Could not write to users file."); //Add the new information to the file
die('You have registered successfully.'); //All done
}
The login section of the file:
elseif($_GET['a'] == "user_login")
{
if(!isset($_GET['username']) || !isset($_GET['pass']))
message("You must specify a username and password.");
$f = fopen($filename, 'r+') or error("Could not open users file.");
@$users = explode("\n", fread($f, filesize($filename)));
for($i = 0; $i < count($users); $i++) {
$users[$i] = explode(" | ", $users[$i]);
}
$user_exists = 0;
for($i = 0; $i < count($users); $i++)
{
if($users[$i][0] == $_GET['username'] && $users[$i][1] == md5($_GET['pass'])) //Same as above, except this time the password must match as well
$user_exists = 1;
}
if($user_exists == 1)
{
//Set two cookies, one with the password and one with the username
setcookie($u_cookie_name, $_GET['username'], 0, $config['cookie_path'], $config['cookie_domain'], false);
setcookie($p_cookie_name, md5($_GET['pass']), 0, $config['cookie_path'], $config['cookie_domain'], false);
header('Location: index.php');
}
else
die('Invalid username or password.');
}
The last section in the file logs the user out if they request it.
elseif($_GET['a'] == "user_logout")
{
//Notice the dates in the past
setcookie($u_cookie_name, "asdf", time() - 1, $config['cookie_path'], $config['cookie_domain'], false);
setcookie($p_cookie_name, "asdf", time() - 1, $config['cookie_path'], $config['cookie_domain'], false);
header("Location: index.php");
}
Next file: global.php. This file is included in the other files of your script and determines if the user is logged in.
$u_cookie_name = 'user'; //Name for the username cookie
$p_cookie_name = 'pass'; //Name for the password cookie
function check_login($user, $pass)
{
global $config;
$filename = "data/users/data.php";
if(isset($user))
{
$f = fopen($filename, 'r+') or die("Could not open users file.");
$users = explode("\n", fread($f, filesize($filename)));
for($i = 0; $i < count($users); $i++) {
$users[$i] = explode(" | ", $users[$i]);
}
$user_exists = 0;
for($i = 0; $i < count($users); $i++) {
if($users[$i][0] == $user)
$password = $users[$i][1];
}
if($pass != $password)
die('Invalid password.'); //Don't let the user in if the password in the cookie does not match their actual password
else
{
$username = $user;
return $username; //Return a variable containing the username
}
}
else
{
$username = ""; //If the user does not exist, set $username to blank
return $username;
}
}
if(isset($_COOKIE[$u_cookie_name]))
$username = check_login($_COOKIE[$u_cookie_name], $_COOKIE[$p_cookie_name]); //Uses the function above to get the username, if the user is logged in
else
$username = 'Guest'; //Otherwise, set the username to Guest
if($username == 'Guest') //This part will be used in our script
{
$t['loginlink'] = '
<li><a href="login.php">Log In</a></li>
<li><a href="login.php?a=user_register">Register</a></li>
';
}
else
{
$t['loginlink'] = '
<li><a href="login.php?a=user_logout">Logout</a></li>';
}
We also need a form for the user to register, register.php.
<?php
include('global.php');
$n1 = rand(0, 10);
$n2 = rand(0, 10);
?>
<form action="login.php">
<div style="width: 75%" class="border">
<table cellpadding="5" align="center">
<tr>
<td>
Username
</td>
<td>
<input type="text" name="username" size="30">
</td>
<tr>
<td>
Password
</td>
<td>
<input type="password" name="pass" size="30 ">
</td>
</tr>
<tr>
<td>
Security Question
</td>
<td>
<?php echo ''.$n1.' plus '.$n2.' = <input type="text" name="check" size="2" maxlength="2" />?'; ?><br>
</td>
</tr>
<tr>
<td>
Submit
</td>
<td>
<input type="hidden" name="a" value="user_register" />
<input type="hidden" name="1" value="<?php echo $n1; ?>" />
<input type="hidden" name="2" value="<?php echo $n2; ?>" />
<input type="submit" value="Register" />
</td>
</tr>
</table>
</div>
</form>
Last, index.php. This file can be replaced with your own code when you use this script.
<h1>My Site</h1>
<ul>
<?php
echo $loginlink;
?>
</ul>
And you’re done! If you use this, feel free to leave a comment on this post, linking to your site.
Make sure you use a .htaccess file to block access to the data file to prevent stealing of passwords and usernames. You can also store it out of the www root.