How can PHP be used to create a password-protected registration system?

To create a password-protected registration system in PHP, you can use a combination of HTML forms, PHP scripts, and MySQL database to store user information securely. Users will need to create an account with a unique username and password, which will be stored in the database. When users log in, their credentials will be checked against the database to verify their identity.

<?php
session_start();

// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Registration form handling
if(isset($_POST['register'])){
    $username = $_POST['username'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    
    $sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
    
    if ($conn->query($sql) === TRUE) {
        echo "Registration successful";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

// Login form handling
if(isset($_POST['login'])){
    $username = $_POST['username'];
    $password = $_POST['password'];
    
    $sql = "SELECT * FROM users WHERE username='$username'";
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        if(password_verify($password, $row['password'])){
            $_SESSION['username'] = $username;
            echo "Login successful";
        } else {
            echo "Invalid username or password";
        }
    } else {
        echo "User not found";
    }
}

$conn->close();
?>