How to set cookies and display the Last visited date and time on the web page in php program

 

Cookies are text files stored on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies.

 

Setting Cookies with PHP

PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag. For each cookie this function has to be called separately.

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

Here is the detail of all the arguments −

·        Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.

·        Value − This sets the value of the named variable and is the content that you actually want to store.

·        Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.

·        Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.

·        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.

·        Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.

Setcookie function

 

<?php

setcookie("username", "s3programmingtech", time()+30*24*60*60);

if(isset($_COOKIE["username"])){

    echo "Hi " . $_COOKIE["username"];

} else{

    echo "Welcome Guest!";

}

?>

 

How to display the Last visited date and time on the web page in php program

 

<html>

<body bgcolor="87ceeb">

<center><h2> Last visited time on the web page</h2></center>

<br>

<?php

//date_default_timezone_set('Asia/Calcutta'); - You can choose any timezone

 

//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(isset($_COOKIE['lastVisit']))

 

{

$visit = $_COOKIE['lastVisit'];

echo "Your last visit was - ". $visit;

}

else

echo "You've got some stale cookies!";

?>

</body>

</html>

 

 

 

Comments

Popular posts from this blog

How to create Animated 3d chart with R.

Linux/Unix Commands frequently used

R Programming Introduction