In: Computer Science
Web Programming:
Explain how a session actually works in PHP, including how the client and server use the session ID to identify the session
Then, compare and contrast cookies and sessions as a means of storing state information for a given user.
Thank you
What is Cookie?
A cookie is a small file with the maximum size of 4KB that the web server stores on the client computer.
Once a cookie has been set, all page requests that follow return the cookie name and value.
A cookie can only be read from the domain that it has been issued from. For example, a cookie set using the domain www.flipkart.com can not be read from the domain fashion.flipkart.com.
Most of the websites on the internet display elements from other domains such as advertising. The domains serving these elements can also set their own cookies. These are known as third party cookies.
A cookie created by a user can only be visible to them. Other users cannot see its value.
Most web browsers have options for disabling cookies, third party cookies or both.
If this is the case then PHP responds by passing the cookie token in the URL.
The diagram shown below illustrates how cookies work.
Here,
1) A user requests for a page that stores cookies
2) The server sets the cookie on the user’s computer
3) Other page requests from the user will return the cookie name and value
Why and when to use Cookies?
Http is a stateless protocol; cookies allow us to track the state of the application using small files stored on the user’s computer.
The path were the cookies are stored depends on the browser.
Internet Explorer usually stores them in Temporal Internet Files folder.
Personalizing the user experience – this is achieved by allowing users to select their preferences.
The page requested that follow are personalized based on the set preferences in the cookies.
Creating Cookies
Let’s now look at the basic syntax used to create a cookie.
<?php setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure], [httponly]); ?>
What is a Session?
Why and when to use Sessions?
Creating a Session
In order to create a session, you must first call the PHP session_start function and then store your values in the $_SESSION array variable.
Let’s suppose we want to know the number of times that a page has been loaded, we can use a session to do that.
The code below shows how to create and retrieve values from sessions
<?php session_start(); //start the PHP_session function if(isset($_SESSION['page_count'])) { $_SESSION['page_count'] += 1; } else { $_SESSION['page_count'] = 1; } echo 'You are visitor number ' . $_SESSION['page_count']; ?>
Output:
You are visitor number 1