How to make login on php

Create secure login for your website using PHP: easy step-by-step guide with example code.

Creating a Login System Using PHP

Creating a login system in PHP is a relatively straightforward process. The first step is to create a form for the user to enter their username and password. This can be done using HTML and a few lines of PHP code. The form should contain two fields - one for the username and one for the password. Both of these fields should be of type "text" and should have the "required" attribute set to true.

Once the form is created, the next step is to create the code to process the form submission. This is done by creating a PHP script that will check the submitted username and password against a database. If the username and password match, then the user is logged in successfully. If not, then an error message is displayed.

The following is an example of a simple PHP login script. This code should be placed in a file called "login.php" and should be placed in the same directory as the form.

<?php
  // Check if the form was submitted
  if($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get the username and password from the form
    $username = $_POST["username"];
    $password = $_POST["password"];

    // Connect to the database
    $db = mysqli_connect("hostname", "username", "password", "database");

    // Check if the username and password match a record in the database
    $query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
    $result = mysqli_query($db, $query);

    // If a match is found, set the session variables and redirect to the home page
    if(mysqli_num_rows($result) == 1) {
      session_start();
      $_SESSION["logged_in"] = true;
      $_SESSION["username"] = $username;
      header("Location: home.php");
    } else {
      // If no match is found, display an error message
      echo "Invalid username or password";
    }
  }
?>

The code above is a very basic PHP login script. It connects to a MySQL database and checks if the submitted username and password match any records in the database. If a match is found, the user is logged in and redirected to the home page. If not, an error message is displayed.

The script can be further customized to include additional features such as user registration, password reset, etc. It can also be modified to work with other databases such as PostgreSQL or MongoDB.

Creating a login system in PHP is relatively straightforward and can be done in a few lines of code. By following the steps outlined above, you should be able to create a basic login system in no time.

Answers (0)