How can PHP be used to implement login functionality with databases and sessions for improved security?

To implement login functionality with databases and sessions for improved security in PHP, you can create a login form where users input their credentials. Upon submission, the PHP code will query the database to verify the credentials. If the credentials are correct, a session will be started and the user will be redirected to a secure page. Here is a sample PHP code snippet to demonstrate this:

<?php
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Connect to database
    $conn = new mysqli('localhost', 'username', 'password', 'database');

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

    // Query database for user
    $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
    $result = $conn->query($query);

    if ($result->num_rows == 1) {
        // Start session and redirect to secure page
        $_SESSION['username'] = $username;
        header("Location: secure_page.php");
    } else {
        echo "Invalid username or password";
    }

    $conn->close();
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Login Form</title>
</head>
<body>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <input type="text" name="username" placeholder="Username" required><br>
        <input type="password" name="password" placeholder="Password" required><br>
        <input type="submit" value="Login">
    </form>
</body>
</html>