PHP USES cookies to count the number of times users visit the code

  • 2020-03-31 20:39:31
  • OfStack

How do I create cookies?
The setcookie() function is used to set cookies.
Note: the setcookie() function must be in < Html> Before the label.

Create your first PHP cookie
When you create a cookie, using the function setcookie, you must specify three parameters. These parameters are setcookie (name, value, expiration) :
Name: the name of your Cookie. You will use this name to retrieve your cookie later, so don't forget it!
Value: the value stored in your cookie. Common values are the username (string) and the last access time (date).
Expiration: on the date, the Cookie will expire and be deleted. If you do not set this expiration date, then it will be considered a session cookie to be deleted and restarted when the browser is restarted.
In this example, we're going to create a Cookie that stores the frequency of the user's last visit as a measure of how often people return to our page. We want people to ignore taking more than two months back to the website, so we will set the expiration date of the Cookie for two months ahead!
 
<?php 
//Calculate 60 days in the future 
//seconds * minutes * hours * days + current time 
$inTwoMonths = 60 * 60 * 24 * 60 + time(); 
setcookie('lastVisit', date("G:i - m/d/y"), $inTwoMonths); 
?> 

If you can't walk in this example there is something involved in the date calculation. It is important that you know how to set a cookie by specifying three important parameters: name, value, and expiration date.
Retrieve your fresh cookies
If your cookie's not yet expired, let's take it from the user's PC and use the appropriate associative array named $_COOKIE. The name of your stored cookie is key and will let you retrieve the value of your stored cookie!
 
<?php 
if(isset($_COOKIE['lastVisit'])) 
$visit = $_COOKIE['lastVisit']; 
else 
echo "You've got some stale cookies!"; 
echo "Your last visit was - ". $visit; 
?> 

Cookies are often used to identify users. A cookie is a small file that the server leaves on the user's computer. Each time the same computer requests a page through a browser, it also sends a cookie. With PHP, you can create and retrieve the value of a cookie.

What if the browser does not support cookies?
If your application involves browsers that do not support cookies, you have to take other steps to pass information from one page to another in your application. One way is to pass data from a form

Related articles: