Home > DeveloperSection > Blogs > PHP Cookies

PHP Cookies


PHP PHP 
Ratings:
1 Comment(s)
 6417  View(s)
Rate this:

PHP Cookies

Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. I.e. 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. Cookies are part of the HTTP header, so cookies must be called before any output is sent to the browser. This is the same limitation that HTTP header has.

With PHP, you can both create and retrieve cookie values.

Creating a Cookie:

The setcookie() function is used to create a cookie in PHP. The setcookie() function must appear before html tag.

Now let’s we have an example, how to create cookie in PHP.

Note: The value of the cookie is automatically URL encoded when sending the cookie, and automatically decoded when received. To prevent URL encoding, use setrawcookie()function instead setcookie() function.

Syntax:

setcookie($name, $value, $expire, $path);

Here, $name specifies the name of cookie, $value specifies the value of cookie, $expire specifies the cookie expiration time and $path specifies the creating path of cookie. The ‘/’ sign is used for creating cookie in current domain.

Example:

<!DOCTYPE html>

<?php

// Creating cookie

   setcookie("TempCookie", "PHPCookie", time()+1*24*60*60,'/') ;

 ?>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

        <title></title>

    </head>

    <body>

        <p>Testing of Cookie Creating </p>

        </br>

        <h3><p>Now retrieve the cookie value </p></h3>

        </br>

        <?php

        // Retrieve the cookie value with $_COOKIE[] function

            echo 'Cookie value is : '.$_COOKIE["TempCookie"];

        ?>

    </body>

</html>

In the example above the expiration time is set to a day (60 sec * 60 min * 24 hours * 1 day).

Note: $_COOKIE[“cookieName”] function is used for retrieving cookie value.


Cookies in PHP

By Rohit Kesharwani on   5 years ago
It will help a lot to the readers while creating a cookie in PHP.

Don't want to miss updates? Please click the below button!

Follow MindStick