By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Creating a login in PHP

How to create a login in PHP, using sessions to remember the username and password.

Edited: 2011-12-09 02:00

To create a login in PHP, we would first need somehow to store the passwords and the usernames. In this Tutorial, we will be storing this directly in the scripts for simplicity.

But before we get started, we would also need somehow to make users stay logged in, so that they don't need to enter their username and password, every time they click on something in the members section.

How to create the login page

The login page is made with HTML forms, and accepts a username and a password. To pass on these values to the script, we would first need to include a name attribute, and give each of the form fields a unique name.

The value of the name attribute, will be picked up by our PHP script, and will be contained in the $_post array. The login page is shown below:

<!DOCTYPE html>
<html lang="en">

    <style type="text/css">
     * {margin:0;padding:0;}
     label {display:block;}



    <form action="login.php" method="post">
     <label>Username</label><input type="text" name="User">
     <label>Password</label><input type="password" name="Password">
     <p><input type="submit"></p>



The PHP login script

To remember the user across pages, we will need to use Sessions, so we will first call session_start, then create a few session variables to take care of the login.

We should also check to see if the username and password was correct, which can be done with a simple if statement.



$_SESSION['UserName'] = $_POST['User'];
$_SESSION['PassWord'] = $_POST['Password'];


Now that we have the basic login script, we should include a PHP if Statement on the main site, to make sure the user is logged in.

So we simply include the below PHP, in the top of our page, before the HTML tag.


$User['loggedin'] = 0;

$UserName = 'BlueBoden';
$Password = 'SecretPassword';

if (($_SESSION['UserName'] === $UserName) && ($_SESSION['PassWord'] === $Password)) {

echo 'Welcome '. $_SESSION['UserName'];
} else {
echo 'Wrong username or password!';

You should call session_start in all pages where you use the session variables.