Login In Php

Here is a simple example of a login system using PHP:

<?php

// Check if the user has submitted their credentials
if (isset($_POST['username']) && isset($_POST['password'])) {
  // Connect to the database
  $db = mysqli_connect('localhost', 'database_user', 'database_password', 'database_name');

  // Get the submitted username and password
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $password = mysqli_real_escape_string($db, $_POST['password']);

  // Look up the user in the database
  $query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
  $result = mysqli_query($db, $query);

  // If the user exists, set a session variable and redirect to the main page
  if (mysqli_num_rows($result) == 1) {
    session_start();
    $_SESSION['username'] = $username;
    header('Location: main.php');
  } else {
    // If the login credentials are invalid, show an error message
    $error = 'Invalid username or password';
  }
}

?>
<!DOCTYPE html>
<html>
<head>
  <title>Login</title>
</head>
<body>
  <?php if (isset($error)) { echo "<p>$error</p>"; } ?>
  <form method="post" action="">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username"><br>
    <label for="password">Password:</label>
    <input type="password" id="password" name="password"><br>
    <input type="submit" value="Submit">
  </form>
</body>
</html>

This code first checks if the user has submitted their login credentials (username and password). If they have, it connects to a MySQL database and looks up the user in the users table. If the user exists, it sets a session variable and redirects the user to the main page. If the login credentials are invalid, it shows an error message.

There are many ways you can improve upon this basic login system, such as adding more robust error handling, using prepared statements to prevent SQL injection attacks, and adding support for password hashing and salting.

Leave a Comment