Core PHP, How To

Count Number of Visits Using PHP Cookies

In this Count Number of Visits Using PHP Cookies task, first, we have to know what are the cookies in PHP. After...

Written by Bikash · 1 min read >

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.

PHP Code to Count Number of Visitors Using Cookies

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

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

PHP Code to Count Number of Visitors Using Cookies on Localhost
PHP Code to Count Number of Visits Using Cookies on Localhost

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 using setcookie() 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:

Happy Coding..!

Was this article helpful?
YesNo
Written by Bikash
My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH. I am a web Programmer by profession and working on more than 50 projects to date. Currently I am working on the web-based project and all the CMS and frameworks which are based on PHP. Profile

3 Replies to “Count Number of Visits Using PHP Cookies”

Leave a Reply

Your email address will not be published. Required fields are marked *