PHP: Cookies.

Techno PHP

The information stored in a web browser as cookies. Next time, when the browser sends the request on the server, it sends stored cookies information on the server and server identify the information .

Now we will learn about how to create cookies, access and delete. We can set the expiry time of cookies.

Example -1 day, 1 month, 1 year. In the session, you have to start the session at the beginning of the page but in the case of cookies, you do not have to start cookie on every page. If you are using cookie then you have to need set a cookie .

Setting cookie|Set the Cookie –

In the PHP to set a cookie, there is a function setcookie() function that is used to set a cookie. The function setcookie() contains six arguments .

Syntax –


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


Name- The name of cookie .
Value -The setcookie() function set the value of the name variable and is the content that you actually want to store .
Expiry- This is a limit to access a cookie . The time may be 1 day ,1 month or more . If you set the time 1 month then you can access the cookie during the 1-month duration. After one month you can not access the cookie.
Domain - This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.
Path- Path specifies the directories for which the cookies id valid .
Domain- This is used to specify the domain name in very large domains and must contains at least two periods to be valid .
Security- It set to be 1 to refers that the cookie should only be sent by secure transmission using HTTPS and else set to 0 which mean cookie can be sent by regular HTTP .
Set the cookie username and mobile email. The cookie will expire after one hour in the below example .

setcookie() function

<?php
setcookie("username", "vishalrana405", time()+3600, "/","", 0);
setcookie("email", "vishalrana405@gmail.com", time()+3600, "/", "", 0);
?>



Delete cookie |Unset Cookie

To delete a cookie you need setcookie() function as well as with it’s name and arguments .



Delete cookie

<?php
setcookie("login","",time()-1);
header("location:index.php")
?>

Complete cookie example (mini project).

Related