Authentication - potatoscript/php GitHub Wiki
Authentication is the process of verifying the identity of a user. In PHP, you can implement authentication using various methods such as sessions, cookies, and tokens. In this section, we'll walk through how to implement a basic authentication system in PHP using sessions.
We will cover:
- User Login Form
- Storing User Credentials (Securely)
- Session Management
- Logout Functionality
- Preventing Unauthorized Access
The first step in implementing authentication is to create a login form where users can enter their credentials.
<form method="POST" action="login.php">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br>
<input type="submit" value="Login">
</form>
- The form sends the data to the
login.php
script using thePOST
method. -
required
attributes ensure that the user cannot submit the form without filling out both fields.
For security reasons, it’s important to store user passwords securely. Instead of storing plain text passwords, you should use hashing functions to store password hashes. PHP provides the password_hash()
function for this purpose.
<?php
$password = "user_password"; // Example password
// Hash the password using bcrypt (the default algorithm)
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Store the hashed password in the database
echo $hashed_password; // Output the hashed password for storage
?>
-
password_hash()
uses bcrypt by default, which is a secure hashing algorithm. - Store the resulting
$hashed_password
in your database instead of the plain text password.
Once the user submits the login form, you will need to verify the submitted password against the stored hash in the database.
<?php
session_start(); // Start the session
// Assuming you've already fetched the stored hash from the database
$stored_hash = '$2y$10$F6QyY2Yy5yUlZ/uvPQCh..IUw3rLgfpJ9l0.WEgZpoODhD4tCWIy'; // Example hash
// Simulate user input from the login form
$username = $_POST['username'];
$password = $_POST['password'];
// Verify the password
if (password_verify($password, $stored_hash)) {
// Password is correct
$_SESSION['username'] = $username; // Store user info in session
echo "Login successful!";
header('Location: dashboard.php'); // Redirect to the dashboard
} else {
// Invalid password
echo "Invalid username or password!";
}
?>
-
password_verify()
checks if the entered password matches the stored hash. -
$_SESSION['username']
stores the user’s information after a successful login, allowing access to authenticated pages. - If the login is successful, you redirect the user to a protected page (e.g.,
dashboard.php
).
PHP uses sessions to maintain state across multiple pages. After the user logs in, you store their information in the session, which can be used to check if the user is authenticated.
<?php
session_start(); // Start the session
// Store user data in session
$_SESSION['username'] = "john_doe";
$_SESSION['user_id'] = 123;
// Access session data
echo "Welcome, " . $_SESSION['username'];
?>
-
session_start()
is called at the beginning of each PHP page where session data is used. - Session variables are used to store user data (e.g., username, user ID) across different pages.
To log the user out, you can destroy the session or unset specific session variables.
<?php
session_start(); // Start the session
// Destroy all session data
session_unset();
session_destroy();
// Redirect to login page
header("Location: login.php");
exit();
?>
-
session_unset()
removes all session variables. -
session_destroy()
destroys the session itself. - After logging out, the user is redirected to the login page.
Once the user is logged in, you should ensure that only authenticated users can access certain pages. This can be done by checking if the session variables are set before allowing access.
<?php
session_start(); // Start the session
// Check if the user is logged in
if (!isset($_SESSION['username'])) {
// Redirect to the login page if not logged in
header("Location: login.php");
exit();
}
// Display protected content
echo "Welcome to the protected page!";
?>
- Before displaying the protected content, we check if the
username
session variable is set. If not, the user is redirected to the login page.
In this section, we covered the basics of implementing authentication in PHP:
- User Login Form: Creating a simple login form for users to enter credentials.
-
Storing User Credentials Securely: Using password hashing (
password_hash()
) for secure storage of passwords. - User Login Logic: Verifying the submitted password against the stored hash.
- Session Management: Using PHP sessions to maintain user authentication across pages.
- Logout Functionality: Implementing logout functionality by destroying session data.
- Preventing Unauthorized Access: Protecting pages from unauthorized users by checking session data.
With these techniques, you can create a simple, secure authentication system for your PHP applications.