$_COOKIE and the concept of cookies with example in php?

Cookies -: Basically, it is used to tracking the purpose of each user. It saves some information in the form of a small text file on a user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. You can create and retrieve the cookie value with the help of PHP.


Create Cookie in PHP

A cookie is created in PHP with the help of setcookie() function.

Syntax -: 

setcookie(cookie_name, cookie_value, cookie_expire_time, path, domain, secure, httponly);


cookie _expire_time -: It is the expire time of cookie means when a cookie is transmitted on client computers and saved the cookie then after that this time is required to delete this cookie according to this time (time in second).

path -: It is used to define the path means path where this cookie is accessible. If the path value is '/' means this cookie is accessible anywhere of this project.


domain -: It is used on a live server, not on the localhost. We can enter the domain name means where this cookie is accessible. 

Note -: If this value is the main domain then it is accessible on subdomain also but this value is subdomain then it is only accessible on this subdomain not all.

secure -: It contains a boolean value. If this value is true means this cookie is transmitted only when secure connection means HTTPSconnection. If this value is false then this cookie is transmitted whenever a connection is HTTP or HTTPS.


httponly -: It also contains a boolean value. If this value is true then this cookie only accessible using a server-side scripting language (PHP). If this value is false then it is accessible using a client-side scripting language(JavaScript) or server-side scripting language(PHP).

Example on localhost server

  • index.php
    • <?php

    • setcookie('name', 'master-tech786', time() + 12, '/');
    • if(isset($_COOKIE['name'])) {
    • echo 'cookie is created';
    • }
    • ?>
  • fetch_cookie.php
    • <?php

    • echo $_COOKIE['name'];

    • ?>



No comments