Cookies in PHP

Cookies in PHP 

  • ·       A text file saved on the user’s system by a Web site.
  • ·       Contains information that the site can retrieve on the user’s next visit and allowing the site to “recognize” to the user and provide an improved / update set of features customized to that specific user.
  • ·       Cookies are usually set in an HTTP header but JavaScript can also set a cookie directly on a browser.
  • ·       It is used to recognize the user.
  • ·       Cookie is created at the server-side and saved to the client browser. Each time when a client sends a request to the server, a cookie is embedded with the request. In such a way, cookies can be received at the server-side.
  • ·       Include displaying site content that is personalized according to the user’s settings, maintaining a record of the content previously viewed by the user, and adding personal user information into site display and layout.
  • ·       Facilitate data transfer between a user and a remote Web site.
  • ·       Defamed in the media as “insecure” and “bad.”
  • ·       In truth, cookies (like any other technology) can certainly be misused, but most Web sites’ usage of cookies is harmless and can be directly linked to enhancing the user experience.

 Some important security features, as follows:

A cookie can only be read by the Web site or domain that created it.

A single domain cannot set more than 20 cookies.

A single cookie cannot exceed 4 kilobytes in size.

The maximum number of cookies that may be set on a user’s system is 300.

 

Note:

Since cookies are stored on the user’s hard drive, developers have very little control over them.

If a user “turn off” cookie in his or her browser, then your cookies will not be saved.

 

Cookies attributes:-

Parameters: The setcookie() function requires six arguments in general which are:


1. Every cookie contains a name-value pair, which represents the variable name and corresponding value to be stored in the cookie.

2. A cookie’s 'expires' attribute defines how long the cookie is valid for. Setting this attribute’s value to a date in the past will usually cause the browser to delete the cookie.

3. A cookie’s 'domain' attribute defines the domain name to be associated with the cookie. Only this domain will be able to access the information in the cookie.

4. A cookie’s 'path' attribute defines which sections of the domain specified in the 'domain' attribute can access the cookie. Setting this to the server root (/) allows the entire domain access to the information stored in the cookie.

5. A cookie’s 'secure' attribute indicates whether a secure HTTP connection is mandatory before the cookie can be accessed.

 

In short, cookies can be created, sent, and received at the server end.

Note: PHP Cookie must be used before <html> tag.

 

Some operations that can be performed on Cookies in PHP:

Creating Cookies:

A cookie is created with the setcookie() function.

Syntax :

setcookie(name, value, expire, path, domain, security);

setcookie("audit ", " hotel ", time()+3600, "/","", 0);

setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); 

// 86400 = 1 day

setcookie("CookieName", "CookieValue");/* defining name and value only*/  

setcookie("CookieName", "CookieValue", time()+1*60*60);//using expiry in 1 hour(1*60*60 seconds or 3600 seconds)  

setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "mydomain.com", 1);  

 

Note: Only the name argument in the setcookie() function is mandatory. To skip an argument, the argument can be replaced by an empty string(“”).

 

Checking Whether a Cookie Is Set Or Not:

Always check the cookie is set or not before accessing its value by the PHP isset() function.

To check whether a cookie “audit” is set or not, the isset() function is executed as follows:

<?php

$cookie_name = "localhost";

$cookie_value = "sjkpgm";

setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

?>

<html>

<body>

 

<?php

if(!isset($_COOKIE[$cookie_name])) {

  echo "Cookie named '" . $cookie_name . "' is not set!";

} else {

  echo "Cookie '" . $cookie_name . "' is set!<br>";

  echo "Value is: " . $_COOKIE[$cookie_name];

}

?>

</body>

</html>

Output:

a cookie is not found!


The first-time cookie is not set. so, if we refresh this page then the cookie is set.


Cookie 'localhost' is set!
Value is: sjkpgm

 

PHP $_COOKIE superglobal variable is used to get a cookie.

It is an associative array that contains a record of all the cookie values sent by the browser in the current request. 

The records are stored as a list where a cookie name is used as the key.

 

 Accessing Cookies with PHP

PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables.

we can use isset() function to check if a cookie is set or not.

<html>
      <head>
      <title>Accessing Cookies with PHP</title>
   </head>
      <body>
            <?php
                               if( isset($_COOKIE["name"]))
                                 echo "Welcome " . $_COOKIE["name"] . "<br />";
         
                                 else
                                 echo "Sorry... Not recognized" . "<br />";
      ?>
         </body>
</html>

 

Modify a Cookie Value

To modify a cookie, just set (again) the cookie using the setcookie() function:

Example

<?php
$cookie_name = "localhost";

$cookie_value = "sjkpgm12345";


setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
  echo "Cookie named '" . $cookie_name . "' is not set!";
else {
  echo "Cookie '" . $cookie_name . "' is set!<br>";
  echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

</body>
</html>

 output:-

Cookie 'localhost' is set!
Value is: sjkpgm12345

 

 Delete a Cookie

The setcookie() function can be used to delete a cookie.For deleting a cookie, the setcookie() function is called by passing the cookie name and other arguments or empty strings but however this time, the expiration date is required to be set in the past.

 <?php  

setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago  

?> 

Output:

set the expiration date to one hour ago

 

Example

<?php
// set the expiration date to one hour ago
setcookie("user""", time() - 3600);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>

</body>
</html>

output:-

Cookie 'user' is deleted.


Cookies are Enabled or disable

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>

Output:-

Cookies are enabled.

 Important Points

  • If the expiration time of the cookie is set to 0, or omitted, the cookie will expire at the end of the session i.e. when the browser closes.
  • The same path, domain, and other arguments should be passed that were used to create the cookie in order to ensure that the correct cookie is deleted. 
  • cookie is valid for a Web site and path, the user’s browser automatically includes the cookie information in a 'Cookie:' header when requesting the site URL.

·       When the user next visits this website domain, the browser will automatically include the following header in its request: Cookie: username=john; location=UK.

 

Find the location and cookies info:-

·       Location: - The exact location of the cookie source on your system depends on which browser and the operating system you’re using.

·       As an example, under Microsoft Windows, Internet Explorer stores its cookies as separate files under C:/Documents and Settings/[username]/cookies, while Mozilla Firefox stores all its cookies in a single file at C:/Documents and Settings/[username]/Application Data/Mozilla/

Firefox/Profiles/[profilename]/cookies.txt.

 

To set multiple cookies, simply by calling setcookie() once for each cookie.

Example:-  which sets three cookies with different validity periods and paths:

<?php

// set multiple cookies

setcookie('username', 'whitewhale', mktime()+129600, '/');

setcookie('email', 'john@somewebsite.com', mktime()+86400, '/');

setcookie('role', 'moderator', mktime()+3600, '/admin');

?>

 

Note:-

Cookies are set using HTTP headers, calls to setcookie() must precede any output generated by your script. A failure to keep to this rule will not only prevent the cookie from being set, but will also generate a series of PHP error messages.

 

 Saving and Restoring User Preferences

·       A simple application that uses cookies to save and restore user preferences.

·       The Web form in the next listing asks the user to select his or her preferences on a long flight, and stores these preferences in a cookie on the user’s system.

·       When the user returns to the page, the previously set preferences are read from the cookie and automatically restored.

 

===================================================   

Post a Comment

0 Comments