Principle:
1. The first user browses a certain page.
2. The server program reads the number of times the page has been viewed from the database or file.
3. Store the number plus one and send it back to the first user.
4. The second user browses a certain page.
5. The server program reads the number of times the page has been viewed from the database or file.
6. Save the number by one and send it back to the second user.
Functions you need to know:
fopen() opens a file
filesize() gets the file size
fseek() moves the file pointer
fgets() gets the content of the line where the file pointer is
fputs() writes the string as the position of the file pointer
fclose() closes the file
file_exists() determines whether the file exists
exec() executes an external program
The simplest counter:
Visitor Counter Prototype /*
(c)1998 David W. Bettis
Here is the copyright information
*/
$counterFile = "counter.txt";
#here Define the counter file
function displayCounter($counterFile) {
$fp = fopen($counterFile,"rw");
#Open the file in read and write mode
$num = fgets($fp,5);
#Get the current number
$num += 1;
#Add 1
print "You are the "."$num"." boring person";
exec( "rm -rf $counterFile");
exec( " echo $num > $counterFile");
#Lazy way, write without using fputs
}
if (!file_exists($counterFile)) {
exec( "echo 0 > $counterFile"); #If the counter file does not exist, create it and set the content to 0
displayCounter($counterFile);
?>
PHP counter simpler version:
< ;?
#The copyright is gone, it’s that simple
$fp=fopen("counter.txt","r+");
flock($fp,3);
#Open the counter file and lock it
$fsize= filesize("count.txt");
$count=fgets($fp,$fsize+1);
$count++;
#Get the number and add one
fseek($fp,0);
fputs($fp, $count);
fclose($fp);
#Write new numbers to the file
echo "You are the $count visitor";
?>
PHP counter graphic version:
Create 10 pictures, I won’t go into details about how to combine digital strings with pictures. Assume that the pictures are 0.gif ~ 9.gif.
....$count is the obtained value
$strcount=strval($count);
$strcount=chop($strcount);
$countlen=$strlen($strcount);
$shtml="";
for ($i=0; $i<$countlen; $i++) {
$shtml. ="
";
}
echo $shtml;
?>
PHP count Server database version:
Use SQL counter, build the table first
CREATE TABLE counter
(
counter int not null,
id int not null
)
INSERT INTO counter(counter,id) VALUE( 0,1)
$c ..., ...);
#MySQL database connection
$sql="select * from counter";
$result=mysql_query($sql,$conn);
$objresult=mysql_fetch_object($result);
$count=$objresult->counter;
$count++;
$sql="update counter set counter=".$count."where id=1";
mysql_query($ sql,$conn);
mysql_close($conn);
echo "You are the $count visitor";
?>
The above has introduced the counter. The simplest PHP program - the counter, including the counter content, I hope it will be helpful to friends who are interested in PHP tutorials.