Login in PHP Secure & Reliable

login in php

How to create login in php functionality

First, create a database to store the user information. You can do this using a tool like phpMyAdmin or by running SQL queries from the terminal. Here’s an example SQL query to create a database named login_system:

CREATE DATABASE login_system;

Then, create a table within that database to store the user information. Here’s an example SQL query to create a table named users with columns for idusername, and password:

CREATE TABLE users (
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    password VARCHAR(255) NOT NULL
);

Create a file index.php

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            background-color: #f2f2f2;
        }
        form {
            width: 400px;
            margin: 50px auto;
            padding: 20px;
            background-color: white;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
            border-radius: 10px;
        }
        input[type="text"], input[type="password"] {
            display: block;
            width: 100%;
            padding: 10px;
            margin-bottom: 20px;
            border-radius: 5px;
            border: none;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
        }
        input[type="submit"] {
            display: block;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            padding: 10px;
            cursor: pointer;
        }
        input[type="submit"]:hover {
            background-color: #3e8e41;
        }
        .error {
            color: red;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <form method="post" action="">
        <h2>Login Form</h2>
        <?php if(isset($login_error)): ?>
            <div class="error"><?php echo $login_error; ?></div>
        <?php endif; ?>
        <label for="username">Username:</label>
        <input type="text" name="username" id="username">
        <label for="password">Password:</label>
        <input type="password" name="password" id="password">
        <input type="submit" name="login" value="Login">
    </form>
</body>
</html>

If the user submits the login form (i.e., the login button is clicked), we retrieve the username and password values from the $_POST array.

We use the password_hash() function to hash the password before querying the database. This is important for security reasons as it ensures that passwords are not stored in plain text.

Next, we query the database for the user account using the SELECT statement and the mysqli_query() function.

We check if the query was successful using mysqli_num_rows() to ensure that there is only one user with that username in the database.

Login logic in PHP paste in top of index.php file

<?php
// Start a session to keep track of the user's login status
session_start();

// Connect to the database (replace with your own servername, username, password, and databasename)
$conn = mysqli_connect("servername", "username", "password", "login_system");

// Check if the connection was successful
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Check if the user submitted the login form
if (isset($_POST['login'])) {
    // Get the input values from the form
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Hash the password before querying the database
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);

    // Query the database for the user account
    $sql = "SELECT * FROM users WHERE username='$username'";
    $result = mysqli_query($conn, $sql);

    // Check if the query was successful
    if ($result && mysqli_num_rows($result) == 1) {
        // Get the user's data from the query result
        $user = mysqli_fetch_assoc($result);

        // Check if the password is correct
        if (password_verify($password, $user['password'])) {
            // Set session variables to store the user's login status and data
            $_SESSION['loggedin'] = true;
            $_SESSION['username'] = $username;
            $_SESSION['id'] = $user['id'];

            // Redirect the user to a protected page
            header("Location: dashboard.php");
            exit;
        } else {
            // Show an error message if the password is incorrect
            $login_error = "Incorrect password";
        }
    } else {
        // Show an error message if the username doesn't exist
        $login_error = "User not found";
    }
}

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

If the query was successful, we fetch the user’s data using mysqli_fetch_assoc() and check if the password is correct using password_verify(). If the password is correct, we set session variables to store the user’s login status and data.

Lastly, we close the database connection using mysqli_close().

Our Recommendation

Avatar of Akhand Pratap Singh

Akhand Pratap Singh

Greetings and a warm welcome to my website! I am Akhand Pratap Singh, a dedicated professional web developer and passionate blogger.

Related Post

Leave a Comment





Newsletter

Subscribe for latest updates

We don't spam.

Loading

Categories