Responsive login form using HTML, CSS and PHP

HTML:-


<!DOCTYPE html>

<html>

<head>

  <meta charset="UTF-8">

  <title>Login Form</title>

  <style>

    body {

      background-color: #f2f2f2;

      font-family: Arial, Helvetica, sans-serif;

    }

    .login-box {

      width: 320px;

      margin: 100px auto;

      background-color: #fff;

      border-radius: 8px;

      padding: 20px;

      box-shadow: 0px 0px 10px #ccc;

    }

    .login-box h2 {

      text-align: center;

      margin-bottom: 30px;

    }

    .login-box input[type="text"],

    .login-box input[type="password"] {

      width: 100%;

      padding: 12px;

      border: 1px solid #ccc;

      border-radius: 4px;

      margin-bottom: 15px;

      box-sizing: border-box;

      font-size: 16px;

    }

    .login-box input[type="submit"] {

      background-color: #4CAF50;

      color: #fff;

      border: none;

      border-radius: 4px;

      cursor: pointer;

      width: 100%;

      padding: 12px;

      font-size: 16px;

    }

    .login-box input[type="submit"]:hover {

      background-color: #45a049;

    }

    .error {

      color: red;

      margin-top: 10px;

    }

  </style>

</head>

<body>

  <div class="login-box">

    <h2>Login</h2>

    <form action="login.php" method="post">

      <label for="username">Username</label>

      <input type="text" id="username" name="username" required>

      <label for="password">Password</label>

      <input type="password" id="password" name="password" required>

      <input type="submit" value="Login">

      <?php if (isset($errorMessage)) { ?>

        <p class="error"><?php echo $errorMessage; ?></p>

      <?php } ?>

    </form>

  </div>

</body>

</html>

In this HTML code, we have created a simple login form that includes a username field, a password field, and a submit button. We have also included some CSS to style the form and center it on the page.

PHP (login.php):


<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Get username and password from form
  $username = $_POST['username'];
  $password = $_POST['password'];

  // Validate username and password
  if ($username === 'admin' && $password === 'password') {
    // Authentication successful, redirect to dashboard
    $_SESSION['username'] = $username;
    header('Location: dashboard.php');
    exit;
  } else {
    // Authentication failed, show error message
    $errorMessage = 'Invalid username or password';
  }
}
?>

In this PHP code, we have first started a session to keep track of the user's login status. We have then checked if the request method is POST, which indicates that the login form has been submitted.

If the form has been submitted, we get the username and password from the form using the $_POST superglobal. We then validate the username and password, in this case checking if they are both equal to hardcoded values. If the authentication is successful

Post a Comment

0 Comments