On this tutorial i’ll show you how to make a simple login portal using PHP for a client area of your website.
First of all you need to make a basic HTML form with a field for the username and a field for the password, these must be named ‘user’ and ‘pass’ respectively. Have this form point to your password protected page and paste the code below above the starting <html> tag of the page.
The script uses an array to specify valid usernames and passwords, so there is no need to set up a database.
Don’t forget to wrap the script below in <?php and ?>
//Start session
session_start();
//Define the users and passwords.
$users = array(
array("username1","password1"),
array("username2","password2"),
array("username2","password2") //Remember to take the comma off the last entry.
);
//Define the log in page if login failed.
$exitpage = "login.htm";
//Then we retrieve the posted values for user and password.
$user = $_POST['user'];
$pass = $_POST['pass'];
//Loop through our defined users
foreach($users as $values){
if($user == $values[0] && $pass == $values[1]){
//If user and pass match any of the defined users
$_SESSION['loggedin'] = true;
};
};
//If the session variable is not true, exit to exit page.
if(!$_SESSION['loggedin']){
header("Location: $exitpage");
exit;
};
If you would like to make multiple pages password protected, use the script below at the top of the page above the <html> tag:
session_start();
if(!$_SESSION['loggedin']){
//Put your log in page url in below
header("Location: loginpage.php");
exit;
};
You can download the source files below to see everything working together: simple-login-script.zip (2.21 KB)
Hi there,
I’ve been scanning all over for a simple PHP script to create a simple login area, and you seem to have it covered. Nice one. Trouble is, I just can’t get your code to work. I’m a numpty starter with no real PHP experience (a huge book to read though). I can re-direct a failed login to a new html page saying click login again, but I can’t seem to get a login to go to my secure page (in your examples ‘clientarea.php’). Am I missing something? All my script is at http://www.martinabeldesign.com
By the way your CSS anti-spam idea is genius! I may well try to get that to work too. Cheers! Martin
Hi Martin, thanks for downloading! Ive made a slight amend to one of the files in the pack, should have sorted your problem!
Hi Ben, this is exactly what I’ve been looking for! Thanks for sharing this.
Hi Ben, i don’t want to sound too cheeky but is there any chance you would be able to expand this script to include some sort of logout button to clear the cookies?
It’s no major thing but I feel it would be a nice addition to the script,
Yes i agree with William, a logout script addition to this would be excellent!
Ok guys will do that when I get a moment.