PHP & MySQL Tutorial
Cookies and Sessions III
- Cookie vs Session
This method is more reliable than using cookies because the user may choose to decline cookies preventing the intended functionality of the PHP script from working.
PHP constant SID contains details of the session ID as a key-value pair. PHPSESSID is the key and the identifier string is the value. This can be added to the URL in a hyperlink as a query string.
<a href="target.php?<?php echo SID; ?>" > link </a>
The first page starts the session and provides a hyperlink to another page with the SID appended as a query string. The session_id() function displays the unique identifier part of the SID on both pages.
#session_start_page.php <?php session_start(); ?> <html> <head> <title>Session Start</title> </head> <body> <a href="session_2nd_page.php?<?php echo SID; ?>" > Go to next page</a><hr> PHPSESSID = <?php echo session_id(); ?> </body> </html>
#session_2nd_page.php <?php session_start(); if( isset( $_SESSION['visit_count']) ) $_SESSION['visit_count']++; else $_SESSION['visit_count'] = 1; ?> <html> <head> <title>Session is running</title> </head> <body> <a href="session_start_page.php?<?php echo SID; ?>" > Go to session start page</a><hr> <p>You have visited this page <?php echo $_SESSION['visit_count']; ?> time(s) in this session.</p> PHPSESSID = <?php echo session_id(); ?> </body> </html>
Let's load the first page.
If we session_start() to continue the current session
Cookies are the typical method for maintaining data with PHP, and it is very simple to store the data with the function, set_cookie() and cookies are probably easier than sessions.
Cookies, however, require the browser to allow cookies to be stored on the client system at the time when more users are becoming reluctant to allow cookies on their machines.
Storing data in session variables, on the other hand, does not rely on the browser settings, so it is more reliable than using cookies. All we have to do is to remember to append the SID session identifier onto each URL in hyperlink, and to call the session_start() function at the beginning of each page.
By changing the php.ini file's session.auto_start() value from 0 to 1, we can remove the need to manual call to session_start(). Now PHP will automatically perform the tasks of the session_start() function whenever a page gets loaded.
In general, it may be better to use sessions rather than cookies if we want to store critical data such as the selected shopping cart items.
Sessions ensure that stored data will be available across the entire website while cookies are disabled. However, sessions will user more server resources to store the data.
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization