PHP Cookies


What are the PHP Cookies

PHP Cookies – for several instances a cookie is used to mark a user. A cookie is a tiny file inserted on the user’s computer by the server. Increasing time a browser page is requested by the same user, the cookie will be sent too. You can generate and retrieve cookie values using PHP.

Most of the internet websites present elements from other realms, including ads. The domains that serve these elements can set their own cookies, too. These are known as cookies by third parties. A user-created cookie can only be available to them. Many people do not see the importance of it. Most web browsers have the option of removing cookies, cookies from third parties, or both. If this is the case then PHP will respond by passing the cookie token in the URL.

Setting Cookie

The setcookie() function is used in PHP to set a cookie. Be sure to call the setcookie() function before any output created by your script will not set a cookie otherwise.

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

Parameters: The setcookie() function usually needs six arguments which are:

Name: It is used to set the cookie title.
Value: It is used to set the cookie value.
Expire: It is used to set the cookie’s expiry timestamp during which access to the cookie is not available.
Path: It is used to define the direction on which the cookie would be accessible on the file.
Domain: This is used to define the domain the cookie is for.
Security: It is used to mean that the cookie will only be forwarded if there is a safe API link.

Below is an example utilizing the setcookie function to construct a cookie called user_name and add Jordan Smith’s meaning to it. This further states that the cookie expires 30 days later.

Example :

PHP Cookies

How to Access PHP cookies value

The superglobal variable PHP $_COOKIE is used to recover a cookie interest. It is usually an associative array that includes a collection of all the values of cookies received by the user in the current search, keyed by the name of the cookie. You may view the individual cookie value using the regular array notation seen in the illustration above.

Output :
Jordan Smith

It is a common idea to test whether or not a cookie has been installed until it accesses its value. You may use the isset() function in PHP to do this. Which is seen in the illustration above.

How to remove the cookie

You can remove a cookie by calling the same setcookie() function with the name of the cookie and some value (such as an empty string), except this time you need to set the expiration date seen in the example above.