This isn't a 100% bullet-proof script. It is just to show the basic idea of how these things work. Later on I will be posting my own extensive script that will be more suited to a live environment.
Here is a revision I did of this script:
<?php
//Include the database connection
include "data.php";
//In order to work with sessions we need use session_start()
session_start();
//Return true if the session is set
function is_logged_in(){
return isset($_SESSION['loggedIn']);
}
//Check to see if they posted a value called "login"
function is_logging_in(){
return isset($_POST['submit']);
}
//Function to show the login form
function loginForm(){
print '
<form method="post">
<strong>Username:</strong> <input type="text" name="username" /><br />
<strong>Password:</strong> <input type="password" name="password" /><br />
<input type="submit" name="submit" value="Login" />
</form>';
}
//See if the login matches a user in the database
function login($username, $password){
//Clean the values of XSS and Injections
$username = trim(htmlentities(strip_tags($username), ENT_QUOTES, 'UTF-8'));
$password = md5(trim(htmlentities(strip_tags($password), ENT_QUOTES, 'UTF-8')));
//Create the MySQL Query
$query = 'SELECT * FROM `registered` WHERE `username` = \''.mysql_real_escape_string($username). '\' AND password = \''. mysql_real_escape_string($password). '\'';
$result = mysql_query($query);
//If we found 1 or more users that matched the login
if(mysql_num_rows($result) > 0) {
$_SESSION['loggedIn'] = true;
header("Location: ". $_SERVER['PHP_SELF']);
exit;
} else {
echo '<strong>Bad login!</strong><br />';
loginForm(); //here we ask the user to login again...
exit;
}
}
//Print "You are loged in" and end the script
function loggedIn(){
die('<h1>You are loged in!</h1>');
}
//Here comes the logic...
//If they are already loged in
if(is_logged_in()){
loggedIn();
//Else if they have submited the form to login
} elseif(is_logging_in()){
login($_POST['username'], $_POST['password']);
//Else this must be the first time they have come so show the login page
} else {
loginForm();
}
?>