- PHP Tutorial
- 24 comments
Create user login in PHP
- Tuesday, 6th December, 2011
- PHP Tutorials
- 161 Comments
PHP is a good alternative when you decide to add a password protected web pages on your web site. You can also use htaccess password protection but with PHP you can create a lot more complex and configurable protection. In this example I will use SESSION variables for login verification.
Lets start with building a configuration file for setting up all the username/password combinations. Create a new passwords.php file and add the following code in it.
Above code creates an $USER array with 3 username/password combinations. We also did a function which will be used later to check if an user is logged in or not. What we need now is a login page (called login.php) where users will enter their username and password and will login.
In order to use the user login feature for your PHP files you need to put that code at the very top of each of your PHP files that need to be protected.
Lets start with building a configuration file for setting up all the username/password combinations. Create a new passwords.php file and add the following code in it.
<?php
$USERS["username1"] = "password1";
$USERS["username2"] = "password2";
$USERS["username3"] = "password3";
function check_logged(){
global $_SESSION, $USERS;
if (!array_key_exists($_SESSION["logged"],$USERS)) {
header("Location: login.php");
};
};
?>
Above code creates an $USER array with 3 username/password combinations. We also did a function which will be used later to check if an user is logged in or not. What we need now is a login page (called login.php) where users will enter their username and password and will login.
<?php
session_start();
include("passwords.php");
if ($_POST["ac"]=="log") { /// do after login form is submitted
if ($USERS[$_POST["username"]]==$_POST["password"]) { /// check if submitted
username and password exist in $USERS array
$_SESSION["logged"]=$_POST["username"];
} else {
echo 'Incorrect username/password. Please, try again.';
};
};
if (array_key_exists($_SESSION["logged"],$USERS)) { //// check if user is logged or not
echo "You are logged in."; //// if user is logged show a message
} else { //// if not logged show login form
echo '<form action="login.php" method="post"><input type="hidden" name="ac" value="log"> ';
echo 'Username: <input type="text" name="username" /><br />';
echo 'Password: <input type="password" name="password" /><br />';
echo '<input type="submit" value="Login" />';
echo '</form>';
};
?>
In order to use the user login feature for your PHP files you need to put that code at the very top of each of your PHP files that need to be protected.
<?php
session_start(); /// initialize session
include("passwords.php");
check_logged(); /// function checks if visitor is logged.
If user is not logged the user is redirected to login.php page
?>
your page code goes here