{"id":626,"date":"2011-10-29T14:55:55","date_gmt":"2011-10-29T09:25:55","guid":{"rendered":"http:\/\/www.binarytides.com\/blog\/?p=626"},"modified":"2011-10-29T14:55:55","modified_gmt":"2011-10-29T09:25:55","slug":"code-simple-php-hit-counter-script","status":"publish","type":"post","link":"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/","title":{"rendered":"Write a simple PHP Hit Counter Script"},"content":{"rendered":"<p>In this tutorial, I am going to show you a simple way to write a Hit Counter script in PHP to save and display the number of visits to your website.<\/p>\t\t<div class=\"display-ad-unit mobile-wide bsa\" style=\"background:#fff3f3; height:315px;\">\n\n<!-- BinaryTides_S2S_InContent_ROS_Pos1 -->\n<style>\n\t@media only screen and (min-width: 0px) and (min-height: 0px) {\n\t\tdiv[id^=\"bsa-zone_1611170977806-3_123456\"] {\n\t\t\tmin-width: 300px;\n\t\t\tmin-height: 250px;\n\t\t}\n\t}\n\t@media only screen and (min-width: 640px) and (min-height: 480px) {\n\t\tdiv[id^=\"bsa-zone_1611170977806-3_123456\"] {\n\t\t\tmin-width: 300px;\n\t\t\tmin-height: 250px;\n\t\t}\n\t}\n<\/style>\n<div id=\"bsa-zone_1611170977806-3_123456\"><\/div>\n\n\n<\/div>\n<!-- Time: 1.0967254638672E-5, Pos: 155, Key: ad_unit_1 -->\n\n\n<p>We will basically store and increment the hits in a file, that can be used to display the total hit count as well.<\/p>\n<p>The code to store the hits follows -<\/p>\n<pre class=\"source-code\" >&amp;lt;?php\n\nclass BT_HitCounter {\n\n\t\/\/ Show &amp;quot;unique&amp;quot; visits only ?\n\tpublic $unique_visits = false;\n\n\t\/\/ Number of hours a visitor is considered as &amp;quot;unique&amp;quot;\n\tpublic $unique_hours = 24;\n\n\t\/\/ Directory to write to (without any trailing slashes)\n\tpublic $hit_count_dir = &#039;hitcount&#039;;\n\n\t\/\/ File to write to\n\tpublic $hit_count_file = &#039;hitcount.txt&#039;;\n\n\t\/\/ Cookie Name\n\tpublic $cookie_name = &#039;bt_hit_count&#039;;\n\n\t\/\/ Record HIT\n\tpublic function recordHit() {\n\n\t\t\/\/ Check whether the target dir exists or not. If not, then create it.\n\t\tif ( isset($this-&amp;gt;hit_count_dir) &amp;amp;&amp;amp; strlen($this-&amp;gt;hit_count_dir) &amp;gt; 0 ) {\n\n\t\t\tif( !file_exists($this-&amp;gt;hit_count_dir) ) {\n\t\t\t\tmkdir($hit_count_dir\/*, 0777, TRUE*\/) or die(&#039;ERROR: Could not create the specified directory!&#039;);  \/\/ http:\/\/php.net\/mkdir\n\t\t\t}\n\n\t\t}\n\n\t\t$hit_count_file = $this-&amp;gt;hit_count_dir . &#039;\/&#039; . $this-&amp;gt;hit_count_file;\n\n\t\t\/\/ Check whether the target file exists or not. If not, then create it.\n\t\tif( !file_exists($hit_count_file) ) {\n\t\t\tfile_put_contents($hit_count_file, &#039;&#039;, LOCK_EX) or die(&amp;quot;ERROR: Can&#039;t write to &amp;quot;$hit_count_file&amp;quot;, please make sure that your path is correct and you have appropriate permissions on the target directory and\/or file!&amp;quot;);\n\t\t}\n\n\t\t\/\/ Get current count from file\n\t\t$hit_count = intval( trim(file_get_contents($hit_count_file)) );\n\n\t\tif ( !$this-&amp;gt;unique_visits || !isset($_COOKIE[$this-&amp;gt;cookie_name]) ) {\n\n\t\t\t\/\/ Increment the hit count by 1 and write to the file\n\t\t\t$hit_count++;\n\t\t\tfile_put_contents($hit_count_file, $hit_count, LOCK_EX) or die(&amp;quot;ERROR: Can&#039;t write to &amp;quot;$hit_count_file&amp;quot;, please make sure that your path is correct and you have appropriate permissions on the target directory and\/or file!&amp;quot;);\n\n\t\t\tif( $this-&amp;gt;unique_visits ) {\n\t\t\t\t\/\/ Send a cookie to the visitor (to track him) along with the P3P compact privacy policy\n\t\t\t\theader(&#039;P3P: CP=&amp;quot;NOI NID&amp;quot;&#039;);\n\t\t\t\tsetcookie($cookie_name, 1, time() + 60 * 60 * $unique_hours);\n\t\t\t}\n\n\t\t}\n\n\t} \/\/ End of Method\n\t\n\t\/\/ Get Total HITs\n\tpublic function getHitCount() {\n\t\t$hit_count_file = $this-&amp;gt;hit_count_dir . &#039;\/&#039; . $this-&amp;gt;hit_count_file;\n\n\t\t\/\/ Get current count from file\n\t\treturn (int) trim(file_get_contents($hit_count_file));\n\t} \/\/ End of Method\n\n} \/\/ End of Class\n\n$hit_obj = new BT_HitCounter();\n\/\/ $hit_obj-&amp;gt;unique_visits = true;\n$hit_obj-&amp;gt;recordHit();<\/pre>\n<p>The script above basically creates the target directory and the file to which the hits needs to be stored is created (if they do not exist) and if there is a failure then the script exits with an error message. Then the value from the file is taken, incremented by 1 and stored back in the file using <a href=\"http:\/\/php.net\/file_get_contents\">file_get_contents<\/a> and <a href=\"http:\/\/php.net\/file_put_contents\">file_put_contents<\/a>.<\/p>\t\t<div class=\"display-ad-unit mobile-wide bsa\" style=\"background:#fff3f3; height:315px;\">\n\n\n<!-- BinaryTides_S2S_InContent_ROS_Pos2 -->\n<style>\n\t@media only screen and (min-width: 0px) and (min-height: 0px) {\n\t\tdiv[id^=\"bsa-zone_1611334361252-4_123456\"] {\n\t\t\tmin-width: 300px;\n\t\t\tmin-height: 250px;\n\t\t}\n\t}\n\t@media only screen and (min-width: 640px) and (min-height: 480px) {\n\t\tdiv[id^=\"bsa-zone_1611334361252-4_123456\"] {\n\t\t\tmin-width: 300px;\n\t\t\tmin-height: 250px;\n\t\t}\n\t}\n<\/style>\n<div id=\"bsa-zone_1611334361252-4_123456\"><\/div>\n\n\n<\/div>\n<!-- Time: 1.8119812011719E-5, Pos: 3992, Key: ad_unit_2 -->\n\n\n<p>If we want to count \"unique\" visits instead of overall hits, then we will just have to set the $unique_visits property of the class to true and that will basically set a cookie to track the visitor who has already open the page in the browser once. the $unique_hours property controls the hours for which a particular user is considered to be \"unique\".<\/p>\n<p>Now, you just need to load the file in your PHP codebase -<\/p>\n<pre class=\"source-code\" >&amp;lt;?php\nrequire &#039;hit_counter.php&#039;;\n\/\/ ... Other Code ...<\/pre>\n<p>Displaying the Hits from the file is fairly easy using the Class.<\/p>\n<pre class=\"source-code\" >...\necho $hit_obj-&amp;gt;getHitCount();\n...<\/pre>\n<p>Tracking Hits for different pages can be accomplished by using some relevant value from $_REQUEST or the Database to create unique files and cookies (cookie name).<\/p>\n<p>You can even use a Relational Database like <a title=\"Sqlite\" href=\"http:\/\/www.sqlite.org\/\">Sqlite<\/a> or <a title=\"MySQL\" href=\"http:\/\/www.mysql.com\/\">MySQL<\/a>\u00a0to track the hits and store other information of the visitors like IP Address, User Agent, Visit Date and Time, which page they have visited, etc.<\/p>\n<p><strong>Final Thoughts<\/strong><\/p>\n<p>Although this was a quick and simple solution to the requirement, there are other great tools\/services like <a title=\"Google Analytics\" href=\"http:\/\/www.google.com\/analytics\/\">Google Analytics<\/a>\u00a0and <a href=\"http:\/\/piwik.org\/\">Piwik<\/a>\u00a0that provides us with \"much\" more features, analytics, reports, charts and information about the visitors to our website or application.<\/p>\n<p>Let me know about your thoughts in comments!<\/p>\n\n<!-- SMARTADDR: No ad unit (ad_unit_3) was added at location: 7492. Content Length: 6238 -->\n<!-- SMARTADDR: No ad unit (ad_unit_4) was added at location: 7492. Content Length: 6331 -->\n<!-- SMARTADDR: No ad unit (ad_unit_5) was added at location: 7492. Content Length: 6424 -->","protected":false},"excerpt":{"rendered":"<p>In this tutorial, I am going to show you a simple way to write a Hit Counter script in PHP to save and display the number of visits to your website. We will basically store and increment the hits in a file, that can be used to display the total hit count as well. The&#8230; <span class=\"read-more\"><a href=\"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/\">Read More &raquo;<\/a><\/span><\/p>\n","protected":false},"author":1,"featured_media":15958,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[322],"tags":[32],"class_list":["post-626","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-tutorial","tag-php"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.1 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Write a simple PHP Hit Counter Script - BinaryTides<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Silver Moon\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/\",\"url\":\"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/\",\"name\":\"Write a simple PHP Hit Counter Script - BinaryTides\",\"isPartOf\":{\"@id\":\"https:\/\/www.binarytides.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.binarytides.com\/blog\/wp-content\/uploads\/2023\/09\/no-thumbnail.jpg\",\"datePublished\":\"2011-10-29T09:25:55+00:00\",\"author\":{\"@id\":\"https:\/\/www.binarytides.com\/#\/schema\/person\/ce24c6ddfa0368f9a08bcf46505884dd\"},\"breadcrumb\":{\"@id\":\"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/#primaryimage\",\"url\":\"https:\/\/www.binarytides.com\/blog\/wp-content\/uploads\/2023\/09\/no-thumbnail.jpg\",\"contentUrl\":\"https:\/\/www.binarytides.com\/blog\/wp-content\/uploads\/2023\/09\/no-thumbnail.jpg\",\"width\":1920,\"height\":1080},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.binarytides.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Write a simple PHP Hit Counter Script\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.binarytides.com\/#website\",\"url\":\"https:\/\/www.binarytides.com\/\",\"name\":\"BinaryTides\",\"description\":\"News, Technology, Entertainment and more\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.binarytides.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.binarytides.com\/#\/schema\/person\/ce24c6ddfa0368f9a08bcf46505884dd\",\"name\":\"Silver Moon\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.binarytides.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/67ac3d58b656585dc0201e900a67f4197eb0c3ef2d1f83dd8f95a0b497cd97da?s=96&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/67ac3d58b656585dc0201e900a67f4197eb0c3ef2d1f83dd8f95a0b497cd97da?s=96&r=g\",\"caption\":\"Silver Moon\"},\"description\":\"A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at binarytides@gmail.com.\",\"url\":\"https:\/\/www.binarytides.com\/author\/admin\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Write a simple PHP Hit Counter Script - BinaryTides","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/","twitter_misc":{"Written by":"Silver Moon","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/","url":"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/","name":"Write a simple PHP Hit Counter Script - BinaryTides","isPartOf":{"@id":"https:\/\/www.binarytides.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/#primaryimage"},"image":{"@id":"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/#primaryimage"},"thumbnailUrl":"https:\/\/www.binarytides.com\/blog\/wp-content\/uploads\/2023\/09\/no-thumbnail.jpg","datePublished":"2011-10-29T09:25:55+00:00","author":{"@id":"https:\/\/www.binarytides.com\/#\/schema\/person\/ce24c6ddfa0368f9a08bcf46505884dd"},"breadcrumb":{"@id":"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/#primaryimage","url":"https:\/\/www.binarytides.com\/blog\/wp-content\/uploads\/2023\/09\/no-thumbnail.jpg","contentUrl":"https:\/\/www.binarytides.com\/blog\/wp-content\/uploads\/2023\/09\/no-thumbnail.jpg","width":1920,"height":1080},{"@type":"BreadcrumbList","@id":"https:\/\/www.binarytides.com\/code-simple-php-hit-counter-script\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.binarytides.com\/"},{"@type":"ListItem","position":2,"name":"Write a simple PHP Hit Counter Script"}]},{"@type":"WebSite","@id":"https:\/\/www.binarytides.com\/#website","url":"https:\/\/www.binarytides.com\/","name":"BinaryTides","description":"News, Technology, Entertainment and more","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.binarytides.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.binarytides.com\/#\/schema\/person\/ce24c6ddfa0368f9a08bcf46505884dd","name":"Silver Moon","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.binarytides.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/67ac3d58b656585dc0201e900a67f4197eb0c3ef2d1f83dd8f95a0b497cd97da?s=96&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/67ac3d58b656585dc0201e900a67f4197eb0c3ef2d1f83dd8f95a0b497cd97da?s=96&r=g","caption":"Silver Moon"},"description":"A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at binarytides@gmail.com.","url":"https:\/\/www.binarytides.com\/author\/admin\/"}]}},"_links":{"self":[{"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/posts\/626","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/comments?post=626"}],"version-history":[{"count":0,"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/posts\/626\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/media\/15958"}],"wp:attachment":[{"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/media?parent=626"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/categories?post=626"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.binarytides.com\/wp-json\/wp\/v2\/tags?post=626"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}