Creating a Login Authentication Website with APM (Apache2, PHP, MySQL)

·

4 min read

Purpose

Create a website with APM (Apache2, Php, Mysql) authentication using PHP's built-in session feature.

  1. Implement login function

  2. Implement main page

    • Only accessible after logging in

    • Show who is currently logged in

  3. Implement logout function

  4. Implement sign-up function

    • Check for duplicate IDs

    • Check for empty fields

The session ID is the user ID.

*Note:

Setting up APM (Apache, PHP, MySQL) Environment on Ubuntu

Set up the Database(MySQL)

Server name = "localhost"

Database name = "test"

Database User name = "root"

Database Password= "1234"

Table name= “users”

first row of table for admin ID: admin

first row of table for admin PWD: admin

Steps

  1. Create a database with the MySQL user:

     mysqladmin -u root create test -p
    
  2. Connect to MySQL user:

     mysql -u root -p
    
  3. Set the root account password (if not already set):

     use mysql;
     ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '1234';
    
  4. Select the database to use:

     use test;
    
  5. Create a table:

     create table users(
         id int primary key auto_increment,
         user_id varchar(255),
         user_pwd varchar(255)
     );
    
  6. Insert a default admin account into the table:

     insert into users (user_id, user_pwd) values ('admin','admin');
    
  7. Verify the data in the table:

     select * from users;
    
  8. Exit the MySQL user:

     quit;
    
  9. Start the MySQL server:

     service mysql start
    
  10. Start the Apache server:

    # Start Apache
    sudo service apache2 start
    # Stop Apache
    sudo service apache2 stop
    # Restart Apache
    sudo service apache2 restart
    

Code

Main.php

<?php
session_start(); // Start session

if(!isset($_SESSION['user_id'])) // If not logged in
{
    header ('Location: ./login.html'); // Redirect to login page
}

echo "<h2>Login Success</h2><br><h2>";
echo $_SESSION['user_id'];
echo ", you have successfully logged in.</h2><br><br>"; // Print user's name
echo "<a href=logout.php>Logout</a>"; // Print logout link

?>

login.html

<html>
<head>
    <title>Login Page</title>
    <meta charset="utf-8">
</head>
<body>
    <form method="post" action="/login_chk.php">
        <div>
            <label for="user_id">ID </label>
            <input type="text" name="user_id"/>
        </div>
        <div>
            <label for="user_pwd">Password </label>
            <input type="text" name="user_pwd"/>
        </div>

        <div class="button">
            <button type="submit">Login</button>
        </div>
    </form>
    <button onclick="location.href='sign_up.html'">Sign Up</button>
</body>
</html>

login_chk.php

<?php
session_start(); // Start session

$id = $_POST['user_id']; // User ID
$pw = $_POST['user_pwd']; // Password

$servername = "localhost"; // Server name
$username = "root"; // User name
$password = "1234"; // Password
$dbname = "test"; // Database name

// Connect to database
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get user info with the entered ID
$sql = "SELECT * FROM users WHERE user_id='$id'";
$result = $conn->query($sql);

// If user info exists
if($result->num_rows == 1){
    $row = $result->fetch_array(MYSQLI_ASSOC);
    // If the entered password is correct
    if($row['user_pwd'] == $pw){
        $_SESSION['user_id'] = $id;
        // If session is successfully saved
        if(isset($_SESSION['user_id'])){
            header('Location: ./Main.php');
        }
        else{
            echo "Session save failed";
        }
    }
    // If the entered password is incorrect
    else{
        echo "Wrong ID or password.";
        header('Location: ./login.html');
    }
}
// If user info does not exist
else{
    echo "Wrong ID or password.";
    header('Location: ./login.html');
}

$conn->close(); // Close database connection
?>

sign_up.html

<html>
<head>
    <title> Sign Up </title>
    <meta charset="utf-8">
</head>
<body>
    <form action = "./sign_up.php" method="post">
        <div>
            <label for="user_id"> ID </label>
            <input type="text" name="user_id"/>
        </div>
        <div>
            <label for="user_pwd"> PW </label>
            <input type="text" name="user_pwd"/>
        </div>

        <div class="button">
            <input type="submit" value="submit">
        </div>
    </form>
</body>
</html>

sign_up.php

<?php
$id = $_POST['user_id']; // ID submitted by the user
$pw = $_POST['user_pwd']; // Password submitted by the user

if($id==NULL || $pw==NULL) // If the user didn't fill out all the fields
{
    echo "Please fill out all the fields";
    echo "<a href=sign_up.html>back page</a>";
    exit();
}

$servername = "localhost"; // Server name
$username = "root"; // User name
$password = "1234"; // Password
$dbname = "test"; // Database name

// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// If the ID already exists
$sql = "SELECT * FROM users WHERE user_id='$id'";
$result = $conn->query($sql);

if($result->num_rows == 1)
{
    echo "ID already exists";
    echo "<a href=sign_up.html>back page</a>";
    exit();
}

// Add new user info to the database
$sql = "INSERT INTO users (user_id, user_pwd) VALUES ('$id', '$pw')";
$signup = mysqli_query($conn, $sql);

// If the signup process is successful
if($signup)
{
    echo "Registration completed.";
}

$conn->close(); // Close the database connection
?>

logout.php

<?php
session_start(); // Start the session

$res = session_destroy(); // Remove all session variables

if($res)
{
    header('Location: ./Main.php'); // If the logout process is successful, redirect to the login page
}
?>

Did you find this article valuable?

Support Han by becoming a sponsor. Any amount is appreciated!