Sessions help manage user-specific data throughout their interaction with a web application. This allows for personalized user experiences by storing user preferences.
To use sessions in PHP, we need to start a session at the beginning of our script:
session_start();
We can store user-specific information in session variables:
$_SESSION['username'] = 'BillJoe_123';
We can access session variables:
$userName = $_SESSION['username'];
We should log out or end the session when the user logs out or after a period of inactivity:
session_destroy();
Cookies are small pieces of data stored on the client’s browser, which are sent back to the server with subsequent requests. They help maintain state information between requests, which is crucial for tracking user activities.
We can set a cookie to store information on the user’s browser:
setcookie('username', 'BillJoe_123, time() + 3600, '/');
Here, username
is the cookie. “BillJoe_123” is the value of the cookie. The expiry time is time() + 3600
. The path for which the cookie is valid is '/'
.
We can access cookie values:
$username = $_COOKIE['username'];
We should remove a cookie when it’s no longer needed:
setcookie('username', '', time() - 3600, '/');