PHP Login Form

A PHP login form is a web form that allows users to enter their login credentials to access a protected area of a website. The form typically includes fields for the user’s email address or username and password.

Here’s an example of how to create a simple PHP login form:

  1. Create a new PHP file on your server called “login-form.php”.
  2. In the file, add the following HTML code to create the login form:
<form method="post" action="process-login.php">
    <label for="email">Email:</label>
    <input type="email" name="email" id="email" required>
    <br>
    <label for="password">Password:</label>
    <input type="password" name="password" id="password" required>
    <br>
    <button type="submit">Login</button>
</form>
  1. In the same directory, create a new PHP file called “process-login.php”.
  2. In the “process-login.php” file, add the following PHP code to handle the form submission:
<?php
    // Get the form data
    $email = $_POST['email'];
    $password = $_POST['password'];
    
    // TODO: Retrieve the user's data from a database or other storage mechanism
    // For this example, we'll assume the user's data is stored in an array
    $user = [
        'email' => 'user@example.com',
        'password' => '$2y$10$4B.Qgawer6jjE7SDHl2rJ.Jg6lL1a/WEU6OJW8Xs/6GJbuCxItrZG', // Hashed password for "password123"
    ];
    
    // Check if the email address exists
    if ($email != $user['email']) {
        header('Location: login-form.php?error=invalid_credentials');
        exit();
    }
    
    // Check if the password is correct
    if (!password_verify($password, $user['password'])) {
        header('Location: login-form.php?error=invalid_credentials');
        exit();
    }
    
    // Start the user session
    session_start();
    $_SESSION['user_id'] = $user['id'];
    
    // Redirect the user to the protected area
    header('Location: protected-area.php');
?>
  1. In the “process-login.php” file, be sure to replace the TODO comment with code that retrieves the user’s data from a database or other storage mechanism.
  2. Save both files to your server.
  3. Test the login form by visiting the “login-form.php” page on your website, filling out the form with the correct credentials, and submitting it. The user should be redirected to the protected area.

Note that this is just a simple example of a PHP login form. There are many other features you can add, such as form validation, CAPTCHA, session timeout, and more. Additionally, storing passwords in plain text is not secure and should never be done in a production environment. Instead, passwords should be hashed and stored securely.