PHP MySQL Login

please click here for more wordpress cource

To create a PHP MySQL login system, you’ll need to follow these general steps:

  1. Create a MySQL database and a table to store user information, such as username and password.
  2. Create a PHP script to handle user authentication. This script will check the submitted login credentials against the database and set a session variable to indicate that the user is logged in.
  3. Create a login form that allows users to enter their username and password.
  4. Create a logout script that destroys the session and logs the user out.

Here is an example code to get you started:

  1. Create the database and table:
CREATE DATABASE users;
USE users;

CREATE TABLE login (
  id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(30) NOT NULL,
  password VARCHAR(30) NOT NULL
);
  1. Create the PHP authentication script:
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Connect to the database
    $servername = "localhost";
    $username = "yourusername";
    $password = "yourpassword";
    $dbname = "users";
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    
    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    // Get username and password from the form
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    // SQL query to retrieve user information
    $sql = "SELECT * FROM login WHERE username='$username' AND password='$password'";
    $result = mysqli_query($conn, $sql);

    // If the user is found, set the session variable and redirect to the home page
    if (mysqli_num_rows($result) == 1) {
        $_SESSION['loggedin'] = true;
        header("location: home.php");
    } else {
        echo "Invalid username or password.";
    }
    mysqli_close($conn);
}
?>
  1. Create the login form:
<!DOCTYPE html>
<html>
<head>
	<title>Login</title>
</head>
<body>
	<h2>Login</h2>
	<form method="post" action="auth.php">
		<label>Username:</label>
		<input type="text" name="username"><br>
		<label>Password:</label>
		<input type="password" name="password"><br>
		<input type="submit" value="Submit">
	</form>
</body>
</html>
  1. Create the logout script:
<?php
session_start();
session_destroy();
header("location: login.php");
?>

Note: This is a basic example to get you started. In a real-world application, you would want to implement additional security measures, such as password hashing and secure cookie handling, to protect against attacks.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *