Skip to content
PHP Logo

How can a PHP beginner implement a login form on the index.php page and redirect to the start page upon successful login?

To implement a login form on the index.php page and redirect to the start page upon successful login, you need to create a form in your index.php file that collects the user's credentials. Upon form submission, validate the credentials in PHP and if they are correct, set a session variable to indicate the user is logged in. Then, redirect the user to the start page using header('Location: start.php').

php
<?php
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = "your_username";
    $password = "your_password";

    if ($_POST["username"] == $username && $_POST["password"] == $password) {
        $_SESSION["loggedin"] = true;
        header('Location: start.php');
        exit;
    } else {
        echo "Invalid username or password";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Login Form</title>
</head>
<body>
    <h2>Login</h2>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <label for="username">Username:</label><br>
        <input type="text" id="username" name="username"><br><br>
        <label for="password">Password:</label><br>
        <input type="password" id="password" name="password"><br><br>
        <input type="submit" value="Login">
    </form>
</body>
</html>