In this Count Number of Visits Using PHP Cookies task, first, we have to know what are the cookies in PHP. After I brief you about PHP cookies you can understand a better way to use a cookie in development.
What are the Cookies in PHP?
Cookies are used track and identify the user on the website. Cookie is a small file which is send by the server and saved on the user’s browser and track that user according their behavior.
Set Cookies Syntax in PHP
1 |
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day |
Now we start with our task where we count how many time that same user visits the website or any web page.
PHP Code to Count Number of Visits Using Cookies
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<html> <head> <title>PHP Code to Count Number of Visitors Using Cookies: PHPCODER</title> </head> <body> <?php if (!isset($_COOKIE['count'])) { echo "Welcome! This is the first time you have viewed this page."; $cookie = 1; setcookie("count", $cookie); }else{ $cookie = ++$_COOKIE['count']; setcookie("count", $cookie); echo "You have viewed this page ".$_COOKIE['count']." times."; } ?> </body> </html> |
Code Explanations:
- On this
if (!isset($_COOKIE['count'])) {
the line we check any cookie is available before or not. OR check our current cookie is set or not. - If no cookie is there then we set the default value which started from one
$cookie = 1;
This value increases whenever the user visits the page. - For an increment of the value of the cookie, we set the pre-increment in PHP,
$cookie = ++$_COOKIE['count'];
then we set usingsetcookie()
function. - In the last we show the counter value of the cookie which shows the number of visits, visit by the user.
Note:
If you want to test it, copy the above code, and create a PHP file and paste it on. Then run it using a localhost server like XAMPP (https://www.apachefriends.org/download.html).
Here is the complete source code and explanations about how we count visitors using PHP cookie.
Also Check:
- How to Convert JSON to Array PHP
- Google Sheet Integration with WordPress without Plugin
- 4 Steps to Upload Image Using Ajax and JQuery
- Pure CSS3 Animated Car
Happy Coding..!
3 Replies to “Count Number of Visits Using PHP Cookies”