0% found this document useful (0 votes)
55 views3 pages

Unit - 5 - PHP Cookie - Session

Uploaded by

Anmol Mogalai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views3 pages

Unit - 5 - PHP Cookie - Session

Uploaded by

Anmol Mogalai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

PHP Cookie

PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the
user.Cookie is created at server side and saved to client browser. Each time when client sends request to
the server, cookie is embedded with request. Such way, cookie can be received at the server side.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.
A simple example of cookies is when you open up a website and your username and password are
auto-filled. Cookies provided your login information to the website. Another example is when you go
online shopping on Amazon and find items that are still in your cart from your last purchasing spree.
PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can access
it by $_COOKIE superglobal variable.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
HERE,

 PHP“setcookie” is the PHP function used to create the cookie.


 “cookie_name” is the name of the cookie that the server will use when retrieving its value from
the $_COOKIE array variable. It’s mandatory.
 “cookie_value” is the value of the cookie and its mandatory
 “[expiry_time]” is optional; it can be used to set the expiry time for the cookie such as 1 hour.
The time is set using the PHP time() functions plus or minus a number of seconds greater than 0
i.e. time() + 3600 for 1 hour.
 “[cookie_path]” is optional; it can be used to set the cookie path on the server. The forward slash
“/” means that the cookie will be made available on the entire domain. Sub directories limit the
cookie access to the subdomain.
 “[domain]” is optional, it can be used to define the cookie access hierarchy
i.e. www.cookiedomain.com means entire domain while www.sub.cookiedomain.com limits the
cookie access to www.sub.cookiedomain.com and its sub domains. Note it’s possible to have a
subdomain of a subdomain as long as the total characters do not exceed 253 characters.
 “[secure]” is optional, the default is false. It is used to determine whether the cookie is sent via
https if it is set to true or http if it is set to false.
 “[Httponly]” is optional. If it is set to true, then only client side scripting languages
i.e. JavaScript cannot access them.
Only the name parameter is required. All other parameters are optional.

Example - File: cookie1.php


<?php
setcookie("user", "Sonoo");
?>
<html>
<body>
<?php
if(!isset($_COOKIE["user"])) {
echo "Sorry, cookie is not found!";
} else { echo "<br/>Cookie Value: " . $_COOKIE["user"]; }
?>
</body>
</html>

Output:
Sorry, cookie is not found!
Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.
Output:
Cookie Value: Sonoo
PHP Delete Cookie
If you set the expiration date in past, cookie will be deleted.
File: cookie1.php
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body></html>

Check if Cookies are Enabled


The following example creates a small script that checks whether cookies are enabled. First, try to create
a test cookie with the setcookie() function, then count the $_COOKIE array variable:

Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {echo "Cookies are disabled.";}
?>
</body></html>

PHP Session
PHP session is used to store and pass information from one page to another temporarily (until user close
the website).
PHP session technique is widely used in shopping websites where we need to store and pass cart
information e.g. username, product code, product name, product price etc from one page to another.
PHP session creates unique user id for each browser to recognize the user and avoid conflict between
multiple browsers.
PHP session_start() function is used to start the session. It starts a new or resumes existing session. It
returns existing session if session is created already. If session is not available, it creates and returns new
session.
PHP $_SESSION is an associative array that contains all session variables. It is used to set and get
session variable values.
Example
File: session1.php
<?php
session_start();
?>
<html>
<body>
<?php
$_SESSION["user"] = "Sachin";
echo "Session information are set successfully.<br/>";
?>
<a href="session2.php">Visit next page</a>
</body> </html>

File: session2.php
<?php
session_start();
?>
<html>
<body>
<?php
echo "User is: ".$_SESSION["user"];
?>
</body> </html>

Session Counter Example


File: sessioncounter.php
<?php
session_start();
if (!isset($_SESSION['counter'])) { $_SESSION['counter'] = 1; } else { $_SESSION['counter']++; }
echo ("Page Views: ".$_SESSION['counter']);
?>

PHP Destroying Session


PHP session_destroy() function is used to destroy all session variables completely.
File: session3.php
<?php
session_start();
session_destroy();
?>

Difference Between Session and Cookies :


Cookie Session
Cookies are client-side files on a local Sessions are server-side files that contain user data.
computer that hold user information.
Cookies end on the lifetime set by the user. When the user quits the browser or logs out of the
programmed, the session is over.
It can only store a certain amount of info. It can hold an indefinite quantity of data.
The browser’s cookies have a maximum We can keep as much data as we like within a session,
capacity of 4 KB. however there is a maximum memory restriction of
128 MB that a script may consume at one time.
Because cookies are kept on the local To begin the session, we must use the session start()
computer, we don’t need to run a function to method.
start them.
Cookies are not secured. Session are more secured compare than cookies.
Cookies stored data in text file. Session save data in encrypted form.
Cookies stored on a limited data. Session stored a unlimited data.
In PHP, to get the data from Cookies , In PHP , to set the data from Session, $_SESSION the
$_COOKIES the global variable is used global variable is used
We can set an expiration date to delete the In PHP, to destroy or remove the data stored within a
cookie’s data. It will automatically delete the session, we can use the session_destroy() function, and
data at that specific time. to unset a specific variable, we can use the unset()
function.

Note: Both cookies and sessions must be started before any HTML tags have been sent to the browser.

You might also like