In this article Storing Session Data in PHP we give the information about Sessions are used to store user data, so that the user’s state persists across every page of the website. In this article we will see how session data is stored and retrieved in PHP.
Storing Session Data in PHP:
The $_SESSION super global variable is used to store session data. We may store user information (user name, email, preferred settings, etc.) during a session and the data remains secure as long as the session is active.
Steps to Store Session Data
- Start Session: Start the session using session_start() function.
- Set Session Variables: Store user data in session using $_SESSION[].
- Retrieve Session Data: Retrieve data from the session.
Example of Storing Session Data
<?php
// Start the session
session_start();
// set the username in the session
$_SESSION[‘username’] = ‘JohnDoe’;
//Display username from session
echo “Hello, ” . $_SESSION[‘username’];
?>
Explanation of Code
- session_start(): The session is started using this function. This ensures that the session is not already active when a new session is started.
- $_SESSION[]: Use $_SESSION[] to store user information. Key and value are added to it. In the example, the user is named in the session.
Retrieving Session Data
You can also retrieve previously stored data from a session.
<?php
session_start(); // start the session
// Retrieve username from session
echo “Hello, ” . $_SESSION[‘username’];
?>
Destroying Session Data
When terminating a session or logging the user out, use session_destroy() to delete all session information.
<?php
session_start(); // start the session
session_destroy(); // end session
?>
Best Practices
Always use secure and encrypted sessions.
End the session when the user logs out.
Do not store data for long periods of time unless necessary.
Conclusion
Session data in PHP can be stored and retrieved securely and easily.
Using sessions it is possible to maintain the user’s state across pages.
User Authentication and Authorization in PHP
Authentication and Authorization are two different but connected aspects that help in providing secure and limited access to users in web applications.
Authentication: Checks who the user is (whether the user is authentic or not).
Authorization: Checks what resources or activities a user can access.
In this article we will understand the process of managing user authentication and authorization in PHP.
Steps to Manage User Authentication and Authorization
- User Registration: Collecting and collecting user information.
- User Authentication: Verifying the user (in the login process).
- Authorization: Controlling user permissions and granting them limited access to the system.
- User Registration
Let’s start registering the user. This includes the username, email and password. The password is usually encrypted.
User Registration Example
<?php
$servername = “localhost”;
$username = “root”;
$password = “”;
$dbname = “mydatabase”;
// Establish MySQL connection
$conn = new mysqli($servername, $username, $password, $dbname);
//check whether the connection is successful or not
if ($conn->connect_error) {
die(“Connection error: ” . $conn->connect_error);
}
// get registration data
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
$name = $_POST[‘name’];
$email = $_POST[’email’];
$password = password_hash($_POST[‘password’], PASSWORD_DEFAULT); // hash the password
//store the data in the database
$sql = “INSERT INTO users (name, email, password) VALUES (‘$name’, ‘$email’, ‘$password’)”;
if ($conn->query($sql) === TRUE) {
echo “Your account was created successfully!”;
} else {
echo “Error: ” .$conn->error;
}
}
$conn->close(); // close the connection
?>
-
User Authentication (Login Process)
User verification is done in the login process. Use password_verify() to re-verify the password hash.
User Authentication Example
<?php
session_start(); // start the session
$servername = “localhost”;
$username = “root”;
$password = “”;
$dbname = “mydatabase”;
// Establish MySQL connection
$conn = new mysqli($servername, $username, $password, $dbname);
//check whether the connection is successful or not
if ($conn->connect_error) {
die(“Connection error: ” . $conn->connect_error);
}
//if login form is submitted
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
$email = $_POST[’email’];
$password = $_POST[‘password’];
$sql = “SELECT * FROM users WHERE email = ‘$email'”;
$result = $conn->query($sql);
if ($result->num_rows> 0) {
$row = $result->fetch_assoc();
if (password_verify($password, $row[‘password’])) {
// user is correct, start session
$_SESSION[‘user_id’] = $row[‘id’];
$_SESSION[‘username’] = $row[‘name’];
echo “You have successfully logged in!”;
} else {
echo “Invalid password!”;
}
} else {
echo “No account found with this email!”;
}
}
$conn->close(); // close the connection
?>
-
User Authorization
Authorization means that the user is restricted to access various resources. For example, limited rights can be granted to different user types, such as admins and normal users.
Example of Authorization
<?php
session_start(); // start the session
// Provide limited access to certain pages if user exists in session
if(isset($_SESSION[‘user_id’])) {
if($_SESSION[‘user_id’] == 1) {
// Privileges for Admin
echo “Admin Area”;
} else {
// normal rights for normal user
echo “Welcome, ” . $_SESSION[‘username’];
}
} else {
echo “Login!”;
}
?>
-
Logout
End the session when the user needs to log out.
Logout Example
<?php
session_start();
session_destroy(); // end session
header(“Location: login.php”); // Redirect to login page
?>
Conclusion
Authentication uses password hashing and SQL queries to correctly verify the user.
Authorization serves to provide special rights or limited access to users.
The combination of both increases the security of web applications and ensures user data privacy.
Some More:
POP- Introduction to Programming Using ‘C’
OOP – Object Oriented Programming
DBMS – Database Management System
RDBMS – Relational Database Management System
Join Now: Data Warehousing and Data Mining