Implementing Login/Logout with PHP
February 10th, 2009Many times when you’re designing a site, you need to password protect certain parts of the site- for example the admin part of the site.
This can be quite easy to do with PHP, by using Cookies.
Start by setting up a file to contain the password etc:
settings.php:
<?php
$admin='Admin1';
$adminpassword='password';
?>
Then create a login file. This file will use a form and cookies to get the username/password from the visitor:
login.php:
<?php
include "settings.php";
$username = $_COOKIE['admin'];
$password = $_COOKIE['password'];
if(isset($_POST[submit]))
{
//check if password is correct, if it is, set the cookie and go to index.php
if($admin == $_POST[login] && $adminpassword==$_POST[password])
{
setcookie("admin", "$_POST[login]", time()+3600);
setcookie("password", "$_POST[password]", time()+3600);
header("Refresh:0; url=index.php");
exit;
}
}
//No admin/password, or the details are wrong... Try again...
?>
<form method = 'post' action='login.php'>
<h2>Welcome back admin</h2>
<?php
if(isset($_POST[submit]))
{
if ($admin != $_POST[login])
{
echo "<b>Invalid login name<br>";
}
elseif ($adminpassword != $_POST[password])
{
echo "<b>Invalid password<br>";
}
}
?>
<table border='0' cellpadding='5' cellspacing='0' style='border-collapse: collapse' bordercolor='#111111' width='70%' id='AutoNumber1'>
<tr>
<td width='20%'>Login Name</td>
<td width='80%'><input type ='text' name='login' size='32'></td>
</tr>
<tr>
<td width='20%'>Password</td>
<td width='80%'><input type='password' name='password' size='32'></td>
</tr>
<tr>
<td colspan='2' align='center'>
<input type='submit' name='submit' value='Login'> <br>
</p>
</td>
</tr>
</table>
</form>
The logout equivalent is quite easy, just blank out the cookies:
logout.php:
<?php
setcookie("admin", "", time()-1800);
setcookie("password", "", time()-1800);
header("Refresh:0; url=login.php");
?>
Finally, make a checklogin page, that sees if the cookies are correct, and if they are not, redirects to the login file:
checklogin.php:
<?php
require "settings.php";
$username = $_COOKIE['admin'];
$password = $_COOKIE['password'];
//Wrong login or password
if ($admin != $username || $adminpassword != $password)
{
header("Refresh:0; url=login.php");
exit;
}
?>
Now, any file you want to add security for, just include “checklogin.php”
For example, if you have a.php:
a.php:
Secret Data
And you wish to password protect it, just change it to this:
<?php
require "checklogin.php"
?>
Secret Data
Thats it! checklogin.php will see if the password is set correctly. If it isn’t it uses the header command to redirect to the login page, so the “Secret Data” underneath is never shown until the user enters the correct login and password…
There is a little bit of hassle setting this up, but once you have- you can password protect any PHP file, just by adding one line!












