"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Tuesday, July 30, 2024

LOGIN FORM

LOGIN FORM 


1. Create the Login Form

Create a file named login.php with the following content:

<?php

session_start();

include 'db_connect.php';

// Check if the user is already logged in

if (isset($_SESSION['user_id'])) {

    header('Location: dashboard.php'); // Redirect to dashboard if logged in

    exit();

}


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

    // Escape user inputs for security

    $email = $conn->real_escape_string($_POST['email']);

    $password = $conn->real_escape_string($_POST['password']);

     // Check if email and password match

    $sql = "SELECT * FROM myGuests WHERE email='$email' and password='$password'";

    $result = $conn->query($sql);

    if ($result->num_rows == 1) {

        $row = $result->fetch_assoc();

             $_SESSION['user_id'] = $row['id'];

            header('Location: dashboard.php');

            exit();

        } else {

            $error = "Invalid email or password.";

        }

    $conn->close();

}

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Login</title>

</head>

<body>

    <h2>Login Form</h2>

    <?php

    if (isset($error)) {

        echo "<p style='color:red;'>$error</p>";

    }

    ?>

    <form action="login.php" method="post">

        <label for="email">Email:</label>

        <input type="email" id="email" name="email" required>

        <br><br>

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

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

        <br><br>

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

    </form>

</body>

</html>

 


Code Explanation :

PHP Script

Session Start:

session_start();
This function initializes a session or resumes the current one based on a session identifier passed via a GET or POST request, or via a cookie. Sessions are used to store user information across multiple pages.

Database Connection:

include 'db_connect.php';
This line includes the db_connect.php file, which presumably contains the code necessary to establish a connection to the database.

Check Login Status:

if (isset($_SESSION['user_id'])) {
    header('Location: dashboard.php');
    exit();
}
Checks if a session variable user_id is set, which would indicate that the user is already logged in.
If the user is logged in, they are redirected to the dashboard.php page, and the script execution stops with exit().

Process Login Form Submission:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = $conn->real_escape_string($_POST['email']);
    $password = $conn->real_escape_string($_POST['password']);
This block runs when the form is submitted via POST method.
The real_escape_string() function is used to sanitize user inputs, preventing SQL injection attacks by escaping special characters in the input strings.

Query Database for User:

$sql = "SELECT * FROM myGuests WHERE email='$email' and password='$password'";
$result = $conn->query($sql);
Executes an SQL query to select all columns from the myGuests table where the email and password match the user input.
Note: Storing passwords in plain text is insecure. Passwords should be hashed using functions like password_hash() and verified with password_verify().

Validate Credentials:

if ($result->num_rows == 1) {
    $row = $result->fetch_assoc();
    $_SESSION['user_id'] = $row['id'];
    header('Location: dashboard.php');
    exit();
} else {
    $error = "Invalid email or password.";
}
Checks if exactly one row is returned, indicating a valid user credential match.
If successful, stores the user id in the session and redirects to the dashboard.
If no match is found, an error message is set.

Close Database Connection:

$conn->close();
Closes the database connection once the operations are complete.
HTML Form
The HTML form allows users to enter their login credentials:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
</head>
<body>
    <h2>Login Form</h2>
    <?php
    if (isset($error)) {
        echo "<p style='color:red;'>$error</p>";
    }
    ?>
    <form action="login.php" method="post">
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>
        <br><br>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required>
        <br><br>
        <input type="submit" value="Login">
    </form>
</body>
</html>

Error Display:

if (isset($error)) {
    echo "<p style='color:red;'>$error</p>";
}
If an error message is set, it is displayed above the form in red.

Form Fields:

The form collects the user's email and password.
Both fields are required for form submission.
Submits the data via POST to the same script (login.php).
Security Considerations
Password Storage:
Passwords should be hashed before storing in the database. Use password_hash() in PHP and verify with password_verify().
Prepared Statements:
Use prepared statements or parameterized queries to protect against SQL injection instead of real_escape_string().
Session Management:
Implement proper session management practices like regenerating session IDs on login to prevent session fixation attacks.
Use HTTPS to encrypt session data transmitted over the network.

Output:



Then now you have to input valid/existing  data that present in your database  ...

Then you go to dashboard.php

2. Create the Dashboard Page

Create a file named dashboard.php to serve as the landing page after a successful login:


<?php

session_start();

// Check if the user is logged in

if (!isset($_SESSION['user_id'])) {

    header('Location: login.php');

    exit();

}

 

// If logged in, display the dashboard

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Dashboard</title>

</head>

<body>

    <h2>Welcome to the Dashboard!</h2>

    <p><a href="logout.php">Logout</a></p>

</body>

</html>

 

 

Code Explanation:

PHP Script

Start the Session

session_start();

Initializes a session or resumes the current one. This is necessary to access session variables, such as $_SESSION['user_id'], which help track user login status across different pages.

Check Login Status

if (!isset($_SESSION['user_id'])) {

    header('Location: login.php');

    exit();

}

This code checks if the session variable $_SESSION['user_id'] is set.

If user_id is not set, it means the user is not logged in, so the script redirects the user to login.php using the header() function.

The exit() function is called to terminate the script after the redirection, ensuring no further code is executed.

Display Dashboard

If the session variable user_id is set, indicating the user is logged in, the script continues to display the HTML for the dashboard.

HTML Content

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Dashboard</title>

</head>

<body>

    <h2>Welcome to the Dashboard!</h2>

    <p><a href="logout.php">Logout</a></p>

</body>

</html>

HTML Structure:

This section contains a simple HTML structure for the dashboard page.

The DOCTYPE declaration specifies that the document is an HTML5 document.

Content:

Welcome Message: Displays a header with the message "Welcome to the Dashboard!".

Logout Link: Provides a link to logout.php, allowing the user to log out and end their session.

Summary

Session Handling: This script uses session handling to check if a user is authenticated before allowing access to the dashboard page.

Redirection: If a user is not authenticated, they are redirected to a login page (login.php).

HTML Page: If authenticated, the user sees a simple dashboard page with a welcome message and a logout link.

Security Considerations

Session Security: Ensure session management best practices, such as regenerating session IDs and securing session data with HTTPS, are followed to prevent session hijacking.

Logout Implementation: The logout.php script should properly destroy the session and redirect users back to a login page or home page after logging out.


Output:



3. Create the Logout Script

Create a file named logout.php to handle user logout:

<?php

session_start();

session_unset();

session_destroy();

header('Location: login.php');

exit();

?>

 

 

Detailed Explanation:

session_start();

Purpose: This function starts a new session or resumes an existing session. Sessions in PHP are used to store user-specific data across multiple pages. It must be called at the beginning of the script before any output is sent to the browser.

Context: By calling session_start(), PHP can access the session data stored on the server, which allows the script to manage user sessions.

session_unset();

Purpose: This function clears all session variables. It essentially removes all data stored in the session.

Context: This is useful when logging out, as it ensures that any user-specific data stored in the session is removed.

session_destroy();

Purpose: This function completely destroys the session data stored on the server. It invalidates the session, effectively making it unusable.

Context: After calling session_destroy(), the session ID is removed and the session data is deleted. This is typically done to ensure that no residual data remains after logout.

header('Location: login.php');

Purpose: This function sends an HTTP header to the browser to redirect the user to another page (in this case, login.php).

Context: After logging out, you usually want to redirect the user to the login page or another page, so they can log in again or access a different part of the site.

exit();

Purpose: This function terminates the script execution immediately.

Context: It ensures that no further code is executed after the redirection header is sent. This is important because if there’s additional code below the header() function, it could interfere with the redirection process.

Summary

This script effectively logs a user out of a session by:

  1. Starting or resuming the session.
  2. Clearing all session variables.
  3. Destroying the session entirely.
  4. Redirecting the user to the login page.
  5. Stopping further script execution to ensure that the redirection is properly handled.

This approach is common in web applications where user authentication and session management are implemented.

4. Database Setup

Make sure you have a myGuests table in your database with columns for id, email, and password. 



No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template