Write a PHP script to keep track of number of times the web page has been access. [Use session and cookies]
here's a PHP script that tracks the number of times a web page has been accessed using sessions and cookies:
Foo © bar 팆 baz ☃ qux<?php
session_start();
$visit_count = 1;
if(isset($_SESSION['visit_count'])){
$visit_count = $_SESSION['visit_count'] + 1;
}
setcookie('visit_count', $visit_count, time() + 86400);
$_SESSION['visit_count'] = $visit_count;
echo "Number of times page has been accessed: " . $visit_count;
?>
In this script, we start a session using session_start()
function. Then, we initialize a variable $visit_count
to 1, which will keep track of the number of times the page has been accessed.
Next, we check if the visit_count
key exists in the session. If it does, we retrieve the current visit count and increment it by 1. Otherwise, we leave it at the default value of 1.
We then set a cookie named visit_count
with the current value of $visit_count
. The cookie will expire in 86400 seconds (1 day).
Finally, we store the updated $visit_count
value in the session and display it to the user.
With this script, every time a user accesses the web page, their visit count will be incremented and stored in both a session and a cookie.