What is the significance of cookies session in web how can a cookie be created and destroyed in php

I have a little confusion about PHP session and session cookies.

Let me ask my question by giving an example of www.example.com.

When I login to www.example.com, it starts a session. So I'm logged in as a user on this website.

Now when I clear cookies in my browser, it deletes all the browser cookie.

My question is - Is the session at www.example.com destroyed when I clear the browser cookies even when I haven't clicked on logout button to destroy the session ?

So that explains what I want to ask.

Does clearing browser cookies automatically destroys PHP session even when you haven't done anything on a website that will call the function to destroy the session ??

asked Dec 21, 2015 at 9:41

1

Why PHP session destroys when clear browser's cookie

After clearing cookies PHP does not destroy session, it just cannot receive session id anymore (which is stored in cookies), so link between session data and current user connection is lost. PHP destroys session later, depending on its' config.

Does clearing browser cookies automatically destroys PHP session even when you haven't done anything on a website that will call the function to destroy the session ??

No, it does not. PHP has limits on session lifetime (see php.ini, session.gc_maxlifetime and session.cookie_lifetime), which basically define session lifetime. In addition to official manual, there's also a good explanation of how these settings influence session lifetime.

answered Dec 21, 2015 at 10:01

If you watch carefully, like through web inspector on Chrome/Firefox etc, then you can see that the PHPSESSIONID is set as a cookie. So if you delete all cookies then I imagine you delete this cookie as well and therefore the session doesn't know what ID to use.

answered Dec 21, 2015 at 9:44

rharveyrharvey

1,9571 gold badge28 silver badges23 bronze badges

It's Mechanisim of Session. You can read more here.

About Session (ussually Server Session). The Server saves all the Session user data on Server and retrives data by Session ID from client (by Cookies).

First time, Client sends a request to Server. The server has not found any Session ID from this request and responses a normal webpage and includes SET-COOKIE: SessionID=xyz

From now, every request from client will include Session ID = xyz (by Cookies).

If you clear Cookies, certainly the Session ID is gone.

answered Dec 21, 2015 at 9:55

The Anh NguyenThe Anh Nguyen

6852 gold badges10 silver badges26 bronze badges

[printfriendly]

What is the significance of cookies session in web how can a cookie be created and destroyed in php

PHP Sessions

A session is a way to store information (in the form of variables) to be used across multiple pages.

Or

The PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.

Starting with PHP session

For starting a php session use the builtin function session_start(). This function is used in the between the php tags, as follow:

Session

<h3>Starting up a session</h3>

<hr />

 session_start()

<?php
session_start(); // start up your PHP session!
?>

Save it as session1.php

Output of the above script

To run the code Open the XAMPP server an start the services like Apache and MySQL. Open the browser and type: http://localhost/yourfoldername/session.php

What is the significance of cookies session in web how can a cookie be created and destroyed in php

Storing a session variable

In this section we will use the correct way to store and retrieve session variables is to use the PHP $_SESSION variable:

PHP script for storing session

<h3>Storing the session in the variable</h3>

<hr />

<?php
session_start();
$_SESSION['views'] = 1; // store session data
echo "Pageviews = ". $_SESSION['views']; //retrieve data
?>

Save it as session2.php

Output of above script

To run the code, Open the XAMPP or wamp server and start the services like Apache and MySQL. Open the browser type: http://localhost/yourfoldername/session2.php

What is the significance of cookies session in web how can a cookie be created and destroyed in php

PHP session with isset() function

Here in this section, session is created with the help of isset(). We create a simple page-views counter. The isset() function checks if the “views” variable has already been set. If “views” has been set, we can increment our counter. If “views” doesn’t exist, we create a “views” variable, and set it to 1

PHP script

<h3>Storing the session in the variable isset()</h3>

<hr />

<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else $_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>

Save it as isset.php

Output

To run the code, Open the XAMPP server and start the services like Apache and MySQL. Open the browser type: http://localhost/yourfoldername/isset.php

What is the significance of cookies session in web how can a cookie be created and destroyed in php

If you hit the same URL again and again the counter for session will incremented.

What is the significance of cookies session in web how can a cookie be created and destroyed in php

What is the significance of cookies session in web how can a cookie be created and destroyed in php

Destroying a PHP session

Destroying a session is also a very important part so if you wish to delete some session data, you can use the unset() or the session_destroy() function.The unset() function is used to free the specified session variable:

<?php
unset($_SESSION['views']);
 ?>

You can also completely destroy the session by calling the session_destroy() function:

<?php
session_destroy();
?>

Note: session_destroy() will reset your session and you will lose all your stored session data.

Tracking Previous Visits to a Page

Let’s now put all this theory in context, by building a simple application that demonstrates how sessions work. This next example uses a session to record every visit made by a user to a Web page. On each visit, the script prints the dates and times of all previous visits and adds a record for the current visit to the session.

Here’s the code (visits.php):

<?php // start session session_start(); ?>

Tracking Previous Visits To A Page

<h2>Tracking Previous Visits To A Page</h2>

<?php
if (!isset($_SESSION['visits'])) {

echo 'This is your first visit.';

} else {

echo 'You previously visited this page on: ';

foreach ($_SESSION['visits'] as $v) {

echo date('d M Y h:i:s', $v) . '';

}

}

?>

<?php
// add current date/time stamp to session array
$_SESSION['visits'][] = time();
?>

To see this script in action, visit the Web page a few times, and you should see a growing list containing records of all your previous visits. This list remains available so long as you don’t close the browser window—so even if you visit a few other sites and then return to this script, you’ll still see the records of all your previous visits. Once you close the browser, however, the session cookie will be destroyed and the list will begin a new.

What is the significance of cookies session in web how can a cookie be created and destroyed in php

This script works by creating a session every time a user visits the page, and storing the timestamp of the user’s visits in the session variable $_SESSION[‘visits’]. On each subsequent visit, the session is recreated, the array containing the timestamps of previous visits is restored, and a foreach loop is used to iterate over this array and print its records in human-readable date and time format.

Cookies in PHP

Now we are going learn how to deal with cookies; first of all we need to know “what is the meaning of cookies” ?

A cookie is object used to identify the user by his/her computer. Cookies are small strings of data created by a Web server but stored on the client. In addition to having names and values, cookies have an expiration time. Cookies are often used to track user information.

‘Or’

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too.

For this purpose you must install a XAMPP server.

Creating Your First PHP Cookie

For creating the very first cookies with PHP, we used the setcookie() function. This is a built in function in php.

Syntax

setcookies(name,value,expiration)

Now we will understand the meaning of these arguments, the explanation of name, value and expiration are given below:

  • name: The name of your cookie. You will use this name to later retrieve your cookie, so don’t forget it.
  • value: The value that is stored in your cookie. Common values are username(string) and last visit(date).
  • expiration: The date when the cookie will expire and be deleted. If you do not set this expiration date, then it will be treated as a session cookie and be removed when the browser is restarted.

This is the PHP script to set the cookies for the particular user :

PHP cookies info

<h3>Setting up cookies</h3>

<hr />

 setcookie('lastVisit', date("G:i - m/d/y"), $oneMonth)

with in php scripting

<hr />

//Calculate 30 days in the future

//seconds * minutes * hours * days + current time

$oneMonth = 60 * 60 * 24 * 30 + time();

setcookie('lastVisit', date("G:i - m/d/y"), $oneMonth);

<hr />

 Cookies enabled............

<?php
$oneMonth = 60 * 60 * 24 * 30 + time();
setcookie('lastVisit', date("G:i - m/d/y"), $oneMonth);
?>

Save it as abc.php.

Output of above php scripting

Type http://localhost/yourfoldername/abc.php at your browser, here your output look like:

What is the significance of cookies session in web how can a cookie be created and destroyed in php

PHP script to retrieve the information

 PHP cookies info

<h3> COOKIES INFORMATION</h3>

<hr />

<?php if(isset($_COOKIE['lastVisit']))
       $visit = $_COOKIE['lastVisit'];
 else
       echo " you got stale cookies!";
 echo "Welcome back!
 You last visited on ". $visit;
 ?>

Save it as ref.php.

Output

Type http://localhost/yourfoldername/ref.php at your browser, here your output look like :

What is the significance of cookies session in web how can a cookie be created and destroyed in php

Destroying the cookies

To destroy the cookie, simply use setcookie again, only set the expiration date to be in the past. Here is an example:

<?php
$past = time() - 60; //this makes the time 60 seconds ago
setcookie(lastVisit, date("G:i - m/d/y"), $past);
?>

Remember: Cookies need to be set in the header. This means they must be sent before any HTML is set to the page, or they will not work.

What is the significance of cookies session in web how can a cookie be created and destroyed in php

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I’m a Certified Engineer on ZEND PHP 5.3, I served my first Fifteen years a number of leadership positions at AmarBebsha Ltd as a CTO, Winux Soft Ltd, SSL Wireless Ltd, Canadian International Development Agency (CIDA), World Vision, Care Bangladesh, Helen Keller, US AID and MAX Group where I worked on ERP software and web development., but now I’m a founder and CEO of TechBeeo Software Company Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute – a leading Training Institute in the country.

It is used to store user identification data. Cookies are stored on the user's local machine. Each time a browser page is requested, the computer sends the cookie alongside for authentication. Cookies are only visible to the user who creates them.

What is the significance of cookies in web?

A cookie is a piece of data from a website that is stored within a web browser that the website can retrieve at a later time. Cookies are used to tell the server that users have returned to a particular website.
Modify a Cookie Value. To modify a cookie, just set (again) the cookie using the setcookie() function: ... .
Delete a Cookie. To delete a cookie, use the setcookie() function with an expiration date in the past: ... .
Check if Cookies are Enabled. The following example creates a small script that checks whether cookies are enabled..
Destroying cookies is upto the browser however you can remove a cookie (which is the same for your app) by setting the date in the past: setcookie($cookie_name, "", 1); Most set the time to 1970 .