Tuesday, 30 May 2023

PHP Code for login page

Here's an example of PHP code for a login page:

<?php

// Start session

session_start();

// Check if user is already logged in

if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {

    header("Location: dashboard.php");

    exit;

}

// Check if form is submitted

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Retrieve form data

    $username = $_POST["username"];

    $password = $_POST["password"];

    // Validate credentials (replace with your own authentication logic)

    if ($username === "admin" && $password === "password") {

        // Authentication successful, set session variables

        $_SESSION['loggedin'] = true;

        $_SESSION['username'] = $username;

        // Redirect to dashboard or desired page

        header("Location: dashboard.php");

        exit;

    } else {

        // Authentication failed, display error message

        $error = "Invalid username or password";

    }

}

?>

<!DOCTYPE html>

<html>

<head>

    <title>Login Page</title>

    <style>

        .error {

            color: red;

        }

    </style>

</head>

<body>

    <h1>Login Page</h1>

    <?php if (isset($error)): ?>

        <div class="error">

            <?php echo $error; ?>

        </div>

    <?php endif; ?>

    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">

        <label for="username">Username:</label>

        <input type="text" name="username" id="username">

        <br>

        <label for="password">Password:</label>

        <input type="password" name="password" id="password">

        <br>

        <input type="submit" value="Login">

    </form>

</body>

</html>

In this example, we have a simple login page with two fields: Username and Password. When the form is submitted, the PHP code validates the credentials (replace with your own authentication logic) and sets session variables if the authentication is successful.

If the user is already logged in (checked using the $_SESSION['loggedin'] variable), they are redirected to the dashboard or desired page (replace "dashboard.php" with the appropriate URL).

If the authentication fails, an error message is displayed.

Note: This code provides a basic structure for a login page and session management. However, it's essential to implement secure authentication practices, such as password hashing and protection against SQL injection, to ensure the security of your application.

Copy Rights Digi Sphere Hub

No comments:

Post a Comment

How can I increase sales with SEO?

To increase sales with SEO ( Search Engine Optimization ), here are some effective strategies you can implement: Keyword research : Conduct ...