How to Utilize PHP Cookie-based Sessions
One intriguing application of cookies is cookie-based sessions. Fortunately, PHP provides an effortless way to create a cookie-based session with the help of session_start()
.
To begin, add the following code snippet to a PHP file and load it in your browser:
1 |
|
Upon executing this code, you will notice a new cookie called PHPSESSID
with an assigned value. This cookie acts as the session ID, which will be sent with every subsequent request. PHP utilizes this session ID to identify the session.
Similar to how we utilized cookies, we can now employ $_SESSION
to store user-sent information. However, unlike cookies, this data is stored on the server side, while the session ID resides client-side.
To illustrate this, consider the following PHP code:
1 |
|
This code works well for simple use cases. However, if you’re dealing with extensive data, incorporating a database becomes necessary.
To clear the session data, you can employ the session_unset()
function. On the other hand, if you wish to clear the session cookie, utilize the following code:
1 | setcookie(session_name(), ''); |
tags: [“PHP”, “cookie-based sessions”, “session_start()”, “session_unset()”, “session cookie”]