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 :
Session Start:
Database Connection:
Check Login Status:
Process Login Form Submission:
Query Database for User:
Validate Credentials:
Close Database Connection:
Error Display:
Form Fields:
Output:
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> |
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:
- Starting or resuming the session.
- Clearing all session variables.
- Destroying the session entirely.
- Redirecting the user to the login page.
- 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.