Text counter in PHP

by Tweak on June 17, 2009
in Php

A counter is an essential part of a site to know how many people are coming to site. Here is an easy way to make a counter. All you need is access to PHP and be able to chmod a directory. We’re going to save the amount of hits in a .dat file, so you don’t even need a mySQL database. First off, you have create a directory and CHMOD it 777 so PHP can write the counter.dat file.

Here is what we have to do:

  1. Use the file_exists() function in PHP and see if the counter.dat file exists. If it does, then open the file using the PHP fopen() function.
  2. Use the PHP fgets() function to find the number of hits there and save it in a variable.
  3. Add one to the variable.
  4. Close the file.
  5. Display the number of hits.
  6. Open the counter.dat file using the fopen() function and save it as a variable.
  7. Use the PHP fputs() function to insert the new number of hits.
  8. Close the file.
  9. If the counter.dat file doesn’t exist, then use the fopen() function and declare it as a variable.
  10. Use the Fputs() function and put a “1″ in there.
  11. Print out that 1 person has come to the page and then close the file.

Here is the code: Read more…

Share and Enjoy:
  • email
  • Print
  • PDF
  • Facebook
  • Digg
  • del.icio.us
  • Google Bookmarks
  • StumbleUpon
  • MySpace
  • Live
  • Twitter
  • Yahoo! Buzz