What's new

Closed Secure Login System with PHP

Status
Not open for further replies.

PhCyber-Vynxz

Honorary Poster
Joined
Feb 11, 2019
Posts
400
Reaction
568
Points
210
Share ko lang mga boss. Masyado mahaba pero detailed steps to hehehehe
Pwede to gamitin sa mga gusto gumawa ng VPN Panel

Secure Login System with PHP and MySQL

For this tutorial I'll be teaching you how you can create your very own secure PHP login system, a login form is what your website's visitors will use to login to your website to access content for logged-in users (such as a profile page).

The Basic and Advanced packages include additional features and a download link to the source code

Contents
  1. Getting Started
    1. Requirements
    2. What You Will Learn in this Tutorial
    3. File Structure & Setup
  2. Creating the Login Form Design
  3. Creating the Database and setting-up Tables
  4. Authenticating Users with PHP
  5. Creating the Home Page
  6. Creating the Profile Page
  7. Creating the Logout Script
1. Getting Started
There are a few steps we need to take before we create our secure login system, we need to set up our web server environment and make sure we have the required extensions enabled.

1.1. Requirements
  • If you haven't got a local web server setup you should download and install You do not have permission to view the full content of this post. Log in or register now..
  • By default, XAMPP will use the latest version of PHP, but if you're are using an older version, make sure to install PHP 5.4+ (includes the MySQLi extension).
1.2. What You Will Learn in this Tutorial
  • Form Design — Design a login form with HTML and CSS.
  • Prepared SQL Queries — How to prepare SQL queries to prevent SQL injection.
  • Basic Validation — Validating form data that is sent to the server (username and password).
  • Session Management — Initialize sessions and store retrieved database results.
1.3. File Structure & Setup
We now need to start our web server and create the files and folders we're going to use for our login system.

  • Open XAMPP Control Panel
  • Next to the Apache module click Start
  • Next to the MySQL module click Start
  • Navigate to XAMPPs installation folder (C:\xampp)
  • Open the htdocs folder
  • Create the following folders and files:

File Structure
\-- phplogin
|-- index.html
|-- style.css
|-- authenticate.php
|-- logout.php
|-- home.php
|-- profile.php
Each file will contain the following:

  • index.html — Login form created with HTML and CSS, we don't need to use PHP in this file so we can just save it as HTML.
  • style.css — The stylesheet for our secure login form.
  • authenticate.php — Connect to the database, validate form data, retrieve database results, and create new sessions.
  • logout.php — Destroy the logged in sessions and redirect the user.
  • home.php — Basic home page for logged in users.
  • profile.php — Select the user's account from our database and display the result.
2. Creating the Login Form Design
We need a login form for our websites users, so they can interact with it and enter their details, we will be using HTML and CSS for this part of the tutorial.

Open up the index.html file with your favorite code editor, we're going to edit this file and add the login form.

Copy and insert the following code (or create your own layout):

Code:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Login</title>
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
    </head>
    <body>
        <div class="login">
            <h1>Login</h1>
            <form action="authenticate.php" method="post">
                <label for="username">
                    <i class="fas fa-user"></i>
                </label>
                <input type="text" name="username" placeholder="Username" id="username" required>
                <label for="password">
                    <i class="fas fa-lock"></i>
                </label>
                <input type="password" name="password" placeholder="Password" id="password" required>
                <input type="submit" value="Login">
            </form>
        </div>
    </body>
</html>

What this will look like if we open it up in our browser:

You do not have permission to view the full content of this post. Log in or register now.
basic-html-login-form-layout.png

Pretty basic right? Let's open up our style.css file and insert the following code:

Code:
* {
      box-sizing: border-box;
      font-family: -apple-system, BlinkMacSystemFont, "segoe ui", roboto, oxygen, ubuntu, cantarell, "fira sans", "droid sans", "helvetica neue", Arial, sans-serif;
      font-size: 16px;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
}
body {
      background-color: #435165;
}
.login {
      width: 400px;
      background-color: #ffffff;
      box-shadow: 0 0 9px 0 rgba(0, 0, 0, 0.3);
      margin: 100px auto;
}
.login h1 {
      text-align: center;
      color: #5b6574;
      font-size: 24px;
      padding: 20px 0 20px 0;
      border-bottom: 1px solid #dee0e4;
}
.login form {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      padding-top: 20px;
}
.login form label {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 50px;
      height: 50px;
      background-color: #3274d6;
      color: #ffffff;
}
.login form input[type="password"], .login form input[type="text"] {
      width: 310px;
      height: 50px;
      border: 1px solid #dee0e4;
      margin-bottom: 20px;
      padding: 0 15px;
}
.login form input[type="submit"] {
      width: 100%;
      padding: 15px;
     margin-top: 20px;
      background-color: #3274d6;
      border: 0;
      cursor: pointer;
      font-weight: bold;
      color: #ffffff;
      transition: background-color 0.2s;
}
.login form input[type="submit"]:hover {
    background-color: #2868c7;
      transition: background-color 0.2s;
}

We need to include our stylesheet in our index.html file, copy and paste the following code to the head section:

Code:
<link href="style.css" rel="stylesheet" type="text/css">

And now if we reload the index.html file in our browser our login form will look awesome:

You do not have permission to view the full content of this post. Log in or register now.
awesome-html-login-form-layout.png

Let's narrow down the form so we can get a better understanding on what's going on.

  • Form — we need to use both the action and post attributes, the action attribute will be set to the authentication file. When the form is submitted, the form data will be sent to the authentication file for processing. The method is to post, this will allow us to process the form data.
    • Input (text/password) — We need to name our form fields so the server can recognize them, so if we set the value of the attribute name to the username, we can use the post variable in our authentication file to get the data, like this: $_POST['username'].
    • Input (submit) — On click the form data will be sent to our authentication file.
3. Creating the Database and setting-up Tables
For this part, you will need to access your MySQL database, either using You do not have permission to view the full content of this post. Log in or register now. or your preferred MySQL database management application.

If you're using phpMyAdmin follow these instructions:

  • Navigate to: You do not have permission to view the full content of this post. Log in or register now.
  • Click the Databases tab at the top
  • Under Create database, type in phplogin in the text box
  • Select utf8_general_ci as the collation
  • Click Create
You can use your own database name, but for this tutorial, I'll use phplogin.

What we need now is an accounts table, this table will store all the accounts (usernames, passwords, emails, etc).

Click the database on the left side panel (phplogin) and execute the following SQL statement:

Code:
CREATE TABLE IF NOT EXISTS `accounts` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(50) NOT NULL,
      `password` varchar(255) NOT NULL,
      `email` varchar(100) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO `accounts` (`id`, `username`, `password`, `email`) VALUES (1, 'test', '$2y$10$SfhYIDtn.iOuCW7zfoFLuuZHX6lja4lF4XA4JqNmpiH/.P3zB8JCa', 'test@test.com');

On phpMyAdmin this should look like:

phpmyadmin-accounts-table.png

The above SQL statement code will create the accounts table with the columns id, username, password, and email.

We also insert a test account with the username: test, and the password: test, you don't really need this account, it's just for testing purposes to make sure our login system works correctly.

4. Authenticating Users with PHP
Now that we have our database setup, we can go ahead and start coding with PHP, we're going to start with the authentication, this will handle the form data that is sent from our index.html file.

Edit authentication.php and insert the following:

Code:
<?php
session_start();
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'phplogin';
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {
    // If there is an error with the connection, stop the script and display the error.
    die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}

The first thing we have to do is start the session, this allows us to remember data on the server, this will be used later on to remember logged in users.

We also connect to the database, we need to connect to the database to check the username and password, make sure to set the variables to your database credentials.

Insert below the above code:



Code:
// Now we check if the data from the login form was submitted, isset() will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
    // Could not get the data that should have been sent.
    die ('Please fill both the username and password field!');
}

This will make sure the form data exists, if the user tries to access the file without submitting the form it will return a simple error.

Insert below the above code:


Code:
// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
    // Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
    $stmt->bind_param('s', $_POST['username']);
    $stmt->execute();
    // Store the result so we can check if the account exists in the database.
    $stmt->store_result();
}

This will prepare the SQL statement that will select the id and password from the accounts table, it will bind the username to the SQL statement, execute, and then store the result.

After:


Code:
$stmt->store_result();

Insert:

Code:
if ($stmt->num_rows > 0) {
    $stmt->bind_result($id, $password);
    $stmt->fetch();
    // Account exists, now we verify the password.
    // Note: remember to use password_hash in your registration file to store the hashed passwords.
    if (password_verify($_POST['password'], $password)) {
        // Verification success! User has loggedin!
        // Create sessions so we know the user is logged in, they basically act like cøøkíés but remember the data on the server.
        session_regenerate_id();
        $_SESSION['loggedin'] = TRUE;
        $_SESSION['name'] = $_POST['username'];
        $_SESSION['id'] = $id;
        echo 'Welcome ' . $_SESSION['name'] . '!';
    } else {
        echo 'Incorrect password!';
    }
} else {
    echo 'Incorrect username!';
}
$stmt->close();


First, we need to check if the query has returned any results, if the username doesn't exist in the database then there would be no results.

If the username exists we can bind the results to the variables: $id and $password.

After we can verify the password with the You do not have permission to view the full content of this post. Log in or register now. function, only passwords that are created with the You do not have permission to view the full content of this post. Log in or register now. function will work.

If you don't want to use any password encryption method, you can simply replace the following code:



Code:
if (password_verify($_POST['password'], $password)) {

With:

Code:
if ($_POST['password'] === $password) {

Finally, if the user is able to login with the correct details our code will create new session variables to remember the user on the server, so when the user visits the home page our PHP code can check if the session variables exist.

Let's try our login to make sure the authentication works correctly, navigate to You do not have permission to view the full content of this post. Log in or register now.

Type in any username and password and click the login button, it should return an error that looks like this:


authentication-incorrect-username.png

Don't worry, it's not broke! If we go back to our login form and enter test for both the username and password fields, we should get something that looks like this:

authentication-loggedin.png



If you get an error, make sure to double check your code to make sure you haven't missed anything or check if the test account exists in your database.

5. Creating the Home Page
The home page is what our logged in users will see, the only way they can access this page is if they're logged in.

Edit the home.php file and insert the following code:

Code:
<?php
// We need to use sessions, so you should always start sessions using the below code.
session_start();
// If the user is not logged in redirect to the login page...
if (!isset($_SESSION['loggedin'])) {
    header('Location: index.html');
    exit();
}
?>

Basically, what happens here is we check if the user is logged in, if they are not we redirect them to the homepage, remember the $_SESSION['loggedin'] variable we defined in the authentication.php file? This is what we use to determine if users are logged in or not.

Now we can add some HTML to our home page. Below the closing tag insert the following code:

Code:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Home Page</title>
        <link href="style.css" rel="stylesheet" type="text/css">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
    </head>
    <body class="loggedin">
        <nav class="navtop">
            <div>
                <h1>Website Title</h1>
                <a href="profile.php"><i class="fas fa-user-circle"></i>Profile</a>
                <a href="logout.php"><i class="fas fa-sign-out-alt"></i>Logout</a>
            </div>
        </nav>
        <div class="content">
            <h2>Home Page</h2>
            <p>Welcome back, <?=$_SESSION['name']?>!</p>
        </div>
    </body>
</html>

TO BE CONTINUED....
 

Attachments

Secured login?

Is this safe from the following:
  • SQL injection attacks
  • XSS attacks
  • XSRF attacks
  • Hosting security
  • Vulnerabilities exploitations
  • Social engineering

The reason I am asking these is I don't want to give the newbies an impression that just because you have a login mechanism does not mean your site is secured
 
Status
Not open for further replies.

Similar threads

Back
Top