Because the underlying HTTP protocol is stateless, keeping state is a vital notion when developing online applications with PHP. This implies that a web server has no intrinsic means of determining if a subsequent request originates from the same client after it has completed processing a client’s request for a page. However, you must monitor a series of requests from a single user in order to implement functionality like shopping carts, user logins, or remembering preferences across pages or even visits. Techniques for keeping state are employed to get around this stateless nature and enable programs to retain user information across many pages and interactions.
In PHP applications, cookies and sessions are two popular ways to preserve state.
PHP Cookies
Browser cookies hold little amounts of data. To identify itself, the server sends a cookie to the browser, which the browser passes to the server on subsequent requests. Cookies help browsers remember data over several visits. The user’s PC contains plain-text files containing this data.
Working with Cookies
The setcookie() function delivers cookies to the browser, and the $_COOKIE superglobal array accesses browser cookies. These are the main ways that PHP handles cookies.
- Setting a Cookie: A cookie is created using the setcookie() function. Setcookie() must be called before your script generates any output since cookies are transmitted as part of the HTTP header. Setcookie(name, value, expire, path, domain, secure, httponly) is the basic syntax. All that is needed is the name.
- name: The cookie’s name.
- value: The amount that will be saved in the cookie.
- expire: A Unix timestamp that indicates the cookie’s expected expiration date. The cookie expires when the browser closes if it is not set.
- path: The directory that the cookie is appropriate for. The cookie is valid for the entire website when it contains a single forward slash (/).
- domain: Helpful for huge domains, this feature allows you to define a domain name.
- secure: The cookie is only transmitted over a secure HTTPS connection if it is set to 1 (or true).
- httponly: Client-side scripts like JavaScript cannot access the cookie if enabled.
- Example of establishing a 30-day-expiring “username” cookie:
- Retrieving a Cookie: PHP automatically makes this information available in the $_COOKIE associative array when a browser requests a cookie from the server. The name of the cookie is the key in the $_COOKIE array, and its value is the value.
- This is an example of how to access a cookie:
- Modifying and Deleting Cookies:To change a cookie, give it a new value and execute setcookie() again with the same name and path. Setting the expiration time to a number in the past and using the same name and location, you run setcookie() to remove a cookie.
- An illustration of how to remove a cookie:
Remember that cookies have constraints despite their simplicity. Users can disable or erase cookies, and certain browsers don’t accept them. Because users may readily read and alter cookies, you should never store important or unencrypted data in them.
Creating Cookies
Use setcookie() to create a cookie. The fundamental syntax is cookie name, value, and expiration time.
Example: Creating a cookie named “Auction_Item” with the value “Luxury Car” that expires in 2 days
<!DOCTYPE html>
<?php
setcookie ( "Auction_Item" , "Luxury Car" , time () + 2 * 24 * 60 * 60 );
?>
<html>
<body>
<?php
echo "cookie is created." ;
?>
<p>
<strong>Note:</strong> You might have to reload the page to see the value of the cookie.
</p>
</body>
</html>
- Setcookie() creates a “Auction_Item” cookie with the value “Luxury Car”.
- Time() + 2 * 24 * 60 * 60 sets the expiration time to 2 days from now.
- Echo validates cookie setting.
- Each HTTP request sends cookies from the user’s browser. Reloading the page after setting the cookie will reveal its value.
- Only the name argument in setcookie() is required.
Introduction to Sessions
A PHP session offers a more dependable and safe method of storing user data throughout a single visit or “session” that spans several pages and requests. Session data is kept on the web server rather than the client’s machine, in contrast to cookies.
A distinct session ID is assigned to each session. PHP creates this ID, which is normally transmitted via a session cookie between the browser and the server.
Working with Sessions
PHP’s built-in methods and the $_SESSION superglobal array make working with sessions simple.
- Starting a Session: The session must be launched before you may access session variables or utilise session capabilities. The session_start() function is used for this. It loads the relevant session data after looking for an existing session ID, which is often stored in a cookie, or, in the event that none is discovered, starts a new session. Due to the possibility of sending a session cookie header, session_start(), like setcookie(), needs to be called before any output is given to the browser.
- An illustration of how to begin a session:
- Storing and Using Session Data: The $_SESSION superglobal array is used to store and retrieve session variables. Although the contents of this array are persistent across sites while the user is logged in, it functions similarly to a standard PHP array.
- An illustration of how to use and set a session variable:
- Ending a Session: When a user shuts down their browser, a session usually comes to an end. Additionally, you can eliminate session variables or explicitly terminate a session.
- The unset() function can be used to eliminate a particular session variable.
- Use session_destroy() to end the session and delete session data associated to the current session ID. The browser’s session cookie is not deleted when session_destroy() deletes the server’s data store.
- An illustration of deleting a session and unsetting a session variable is as follows:
Common Uses and Security
Sessions are essential for preserving state and making possible functions such as:
- User Authentication: Possibly the most popular use is monitoring a user’s authorisation level and if they are logged in. You save a marker (such as a user ID or boolean flag) in $_SESSION following a successful login, and then look for this marker on sites that need authentication.
- Shopping Carts: Keeping track of what a customer has put in their cart.
- User Preferences: Recalling parameters such as theme, language, or particular filtering choices.
Security Points to Remember: There are security considerations even though session data isn’t kept on the client like cookies are:
- Avoid storing private data in cookies: As previously stated, it is not secure to store authentication information (such as passwords) directly in cookies. For this, sessions work better.
- A security flaw known as “session fixation” allows an attacker to fool a user into using a session ID they are aware of. Regenerating the session ID once a user logs in is frequently used to guard against this.
- Protecting Session Files: The server’s files containing session data must be shielded from unauthorised access.
- Data in $_SESSION: Even if the data is saved on the server, it should still be handled carefully when it is accessed, particularly if it came from previously stored user input. According to the general security principle discussed earlier, it is a good idea to filter and validate session data before using it.
By storing sensitive data on the server, sessions offer a more secure method of state maintenance and release you from many of the limits of cookies, including size restrictions.
Combining Cookies and Sessions
Cookies are frequently used in the background by PHP’s built-in session-tracking system to manage the session ID. PHP tries to transmit a new session ID as a cookie or read a session ID from a cookie (sometimes called PHPSESSID) when you call session_start().
You may manage several forms of persistent data by combining cookies and sessions. PHP built-in sessions can handle states that should be forgotten after the user exits the website, such as the contents of the shopping cart or the current page. Cookies can be used to store information that should be retained between user visits, like a distinct user ID. When a user returns to the website, you can access more permanent data (such as display preferences or postal address) from a database using a persistent user ID that is saved in a cookies.
Difference Between Sessions and Cookies
Sessions | Cookies |
---|---|
Data is stored on the server. | Data is stored on the client’s browser. |
Data is available as long as the session is active (until the browser is closed or the session expires). | Cookies can persist for a specified period, even after the browser is closed. |
No significant size limit. | Limited to approximately 4KB of data. |
More secure because the data is stored on the server. | Less secure, as data is stored on the client’s machine. |
The session lasts until the browser is closed or the session expires. | Cookies can have an expiry time set during creation. |
Session data is only accessible on the server side. | Cookie data is accessible on both the client and server sides. |
Can store sensitive information securely (e.g., user authentication). | It can be intercepted or manipulated if it is not encrypted. |
Storing sensitive or temporary data (e.g., login credentials, shopping cart data). | Remembering user preferences, tracking users, or remembering non-sensitive information between sessions. |
Supports transactions to ensure data integrity with in the session. | No support for transactions, as cookies are stored on the client. |
Maintains state over multiple pages by storing data in the session. | The stored data persists between sessions, allowing users to maintain their state across visits. |