How to create Viewer or visitor counter for our website through php ?

Description:- Below is the code through which we can easily make viewer counter for our website. It will also work offline on your local machine, just refresh the page and it will increase the count. Through this you can count the views on your website. I call this viewer counter.

<?php
$file = "countfile.txt";
$a = file_get_contents($file);
$r = $a+1;
$create = fopen($file,"w");
fwrite($create,$r);

?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View counts</title>
<style>
.view{background:rgba(0,0,0,1); color:rgba(0,204,255,1); border:2px inset rgba(153,153,153,1); width:100px;  text-align:center; padding:10px; font-size:2em;}
</style>
</head>
<body>
<center>
<h2>You are viewer number:</h2> <div class="view"><?php echo $r; ?></div>
</center>
</body>
</html>

*Note:- When you run this code in your web browser, first time it will show a warning i.e;
” Warning: file_get_contents(countfile.txt) [function.file-get-contents]: failed to open stream ” because the file countfile.txt is not yet created. But after refreshing it second time the above php code will generate the countfile.txt automatically and it won’t show the warning again. And I styled the div according to me you can style it according to your need. Have fun guys.
Happyyyy Coding !
Happyyyy Coding !
😉

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s