Vectorials
Flash Perfection
3D Lessons
Tutorialkit
Markup Tutorials
Learn PHP
network
adv banner
Web Programming  Home Web Programming PHP PHP Counter
rss

PHP Counter

Author: Kyscorp.com More by this author


PHP CounterA counter is a simple yet essential script when developing web pages.

First of all, we need a file where to store the data ( a simple text file). This file must be CHMODed to 777 (under Linux)

Let's name this file "data.txt". Do not forget to include it into the same directory as the PHP script.

Open "data.txt" and enter the initial value you want the counter to start from. Ex: 200 and save it!

Do not write anything else simply the number with no spaces or so!!

Now we start our PHP script :

<?
//Here's the script
?>

Firstly, we do have to read the content of data.txt, increment the number of visits, save the file then display the number.

1/ open the file as readonly only to get the number stored into it.

$fp=fopen("data.txt","r"); //"r" means Readonly

Now we ought to read the file and store its content into $number

$number=fread($fp, filesize("data.txt"));

We close the file

fclose($fp);

We increment $number;

$number++;

We reopen the file and erase its content. We use "w+" mode which allows us to write on file.

$fp=fopen("data.txt","w+");

We write $number into the file then close it:

fwrite($fp,$number);
fclose($fp);

Now we display the number :

echo $number;

Here's the full script :

<?
$fp=fopen("data.txt","r"); //"r" means Readonly
$number=fread($fp, filesize("data.txt"));
fclose($fp);
$number++;
$fp=fopen("data.txt","w+");
fwrite($fp,$number);
fclose($fp);
echo $number;
?>


Rate this Material: Bad 1 2 3 4 5 Excellent
print this page tell a friend subscribe to newsletter subscribe to rss

Add comments to "PHP Counter"