Thursday, January 30, 2025
HomeTechHow to create admin login page using PHP?

How to create admin login page using PHP?

Creating an admin login page in PHP involves several steps. Below is a simple example that demonstrates how to create a basic login page for an admin user, with authentication, password validation, and session handling.

Step 1: Create the Database

First, you need to set up a database to store the admin credentials (username and password).

CREATE DATABASE admin_db;

USE admin_db;

CREATE TABLE admins (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(100) NOT NULL,
    password VARCHAR(255) NOT NULL
);

-- Example of an admin user (password should be hashed)
INSERT INTO admins (username, password) VALUES ('admin', 'your_hashed_password');

Note: Always store passwords in a hashed format (e.g., using password_hash() in PHP), not in plain text.

Step 2: Create the Login Form

Create an HTML form for the admin login page (login.php):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login</title>
</head>
<body>
    <h2>Admin Login</h2>
    <form action="login_process.php" method="POST">
        <label for="username">Username:</label><br>
        <input type="text" id="username" name="username" required><br><br>

        <label for="password">Password:</label><br>
        <input type="password" id="password" name="password" required><br><br>

        <button type="submit">Login</button>
    </form>
</body>
</html>

Step 3: Handle the Login Logic (login_process.php)

Now, write the PHP code to handle the form submission, validate the credentials, and start a session if the login is successful.

<?php
session_start();

// Database connection
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'admin_db';

$conn = new mysqli($host, $user, $pass, $dbname);

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Prevent SQL Injection
    $username = $conn->real_escape_string($username);

    // Query to check if the admin exists
    $sql = "SELECT * FROM admins WHERE username = '$username'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();

        // Verify the password using password_verify
        if (password_verify($password, $row['password'])) {
            // Password is correct, start a session
            $_SESSION['admin_id'] = $row['id'];
            $_SESSION['admin_username'] = $row['username'];

            // Redirect to admin dashboard
            header("Location: dashboard.php");
            exit();
        } else {
            echo "Invalid password.";
        }
    } else {
        echo "Admin not found.";
    }
}
$conn->close();
?>

Step 4: Create the Admin Dashboard (dashboard.php)

After a successful login, you can create a simple dashboard.php page to display a message or admin interface.

<?php
session_start();

// Check if the user is logged in
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</title>
</head>
<body>
    <h1>Welcome, <?php echo $_SESSION['admin_username']; ?>!</h1>
    <p>This is your admin dashboard.</p>

    <a href="logout.php">Logout</a>
</body>
</html>

Step 5: Logout (logout.php)

To allow the admin to log out, create a simple logout script:

<?php
session_start();
session_unset();
session_destroy();

header("Location: login.php");
exit();
?>

Step 6: Hashing the Password (Optional)

If you need to hash the password before inserting it into the database, use the password_hash() function when creating the admin user:

$hashed_password = password_hash('admin_password', PASSWORD_DEFAULT);

Then insert this hashed password into the database instead of plain text.

See also  Introduction to Amazon Web Services

Conclusion

This is a basic structure for an admin login system in PHP. You can extend this with features like:

  • Redirecting users who are not logged in
  • Limiting login attempts
  • Password recovery
  • Admin roles and permissions
See also  Difference Between Decimal and Binary Number System

Make sure to use proper security measures when handling user data, including password hashing, input sanitization, and session management.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x