PHP Login Script / form

PHP Add comments

Today I have coded a php login script for you guys to have a look at. It is in its most basic form only using variables stored in the script as verification of the users identity but you could adapt it easily for use with a database.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
/*
Simple PHP login script
--> By Andrew Pryde
--> http://www.pryde-design.co.uk
*/
 
// EDIT VARS
$username = "1";
$password = "1";
// STOP EDIT
 
// start a session (needed for detecting if the user is logged in or not)
session_start();
 
// function to login the user or tell them that the username // pass is incorrect
function login ($user, $pass)
{
global $username, $password;
if (($user == $username) && ($pass == $password))
{
$_SESSION['LOGGED_IN'] = true;
}
else
{
print "The password and or Username were incorrect";
}
}
 
// function to print the html login form
function print_form ()
{
$form  = '<form action="'.htmlentities($_SERVER['PHP_SELF']).'" method="post">';
$form .= 'Username:<input name="user" type="text" />Password:<input name="pass" type="password" />';
$form .= '<input name="Submit" type="submit" value="Submit" /></form>';
print $form;
}
if ($_SESSION['LOGGED_IN'] == true && empty($_GET['logout']))
{
print 'Members area....<a href="'.htmlentities($_SERVER['PHP_SELF']).'?logout=yes">Logout</a>';
}
elseif (isset($_POST['user']) && isset($_POST['pass']))
{
login ($_POST['user'], $_POST['pass']);
if ($_SESSION['LOGGED_IN'] == true)
{
print 'Members area....<a href="'.htmlentities($_SERVER['PHP_SELF']).'?logout=yes">Logout</a>';
}
}
elseif (($_SESSION['LOGGED_IN'] == true) && ($_GET['logout'] == "yes"))
{
session_destroy();
print 'You have been logged out... <a href="'.htmlentities($_SERVER['PHP_SELF']).'">Login</a>';
}
else
{
print_form();
}
?>

The code should explain its self as I commented it quite vigorously but if not feel free to comment below and or email me with any problems.

Just as a foot note Asome1 will be glad to see that I have used htmlentites() on the PHP_SELF variables in this script if you don’t know what I’m talking about you should read this post .

I have made a newer version of this script called Advanced Mysql / PHP database backed login script I would suggest you have a look at it as it includes some more useful features not seen in this version of the script.

- Andrew

Leave a Reply

WP Theme & Icons by Pryde Design
Entries RSS Comments RSS Log in