A home-rolled php text counter

A home-rolled php text counter

Here's the code for a self-starting visitor counter for your site: You don't have to do anything; it creates its own counter file, based on the name of the file it's in. An index.php page will create an "indexcount.dat" file, etc.

Yeah this is geeky, and very much coding 101, but hey. I like Php, even though It's not as sexy as Ruby.

(stick this inside php tags)

(open phptag)

//text-file based counter (make sure the enclosing folder is chmod 775)

$countfile = pathinfo(__FILE__, PATHINFO_FILENAME)."count.dat" ; //creates a separate count file named for any page it is on.

$resetdate = strftime("%D",time()) ; // creates a human-readable date

$count=file($countfile, FILE_IGNORE_NEW_LINES); // reads the count file

if(count($count)<2) { $count = array($resetdate, $visitors = 0 ) ; } //this initalizes an empty count file

$countdate= array_shift($count) ; //takes the first line and uses it for the date

if(empty($countdate)) { $countdate=$resetdate ; } //this is in case the first line of the file is empty

$visitors = ++$count[0] ; // increments the visitors number

if(!is_numeric($visitors)) { $visitors=1 ; } // handles error if something weird is on the visitor line

if(!file_put_contents($countfile,$countdate."\n".$visitors)) { // error handling file permissions

echo 'Can not write to '.$countfile' chmod to 755? ' ; }

echo $visitors.' visitors since '.$countdate ; // the visitor message

(close php tag)

-----------

as seen here

Type: Geekiness  Contact   ^top         < Prev   Current   Next >   of 20   Posted: 11/29/09     ID: 1259530275 # 1259530275