iNET Interactive - Online Advertising Agency
          
   Home    Authors    About    Login    Contact Us
   Search:   
Advanced Search     
  Articles

  ASP (26)
  ASP.NET (19)
  C and C++ (4)
  CFML (2)
  CGI and Perl (16)
  Flash (2)
  Java (7)
  JavaScript (28)
  PHP (92)
  MySQL (13)
  MSSQL (3)
  HTML (34)
  SEO (9)
  Visual Basic (12)
  CSS (13)
  SSI (5)
  XML (12)
  C# (14)

  Developer News

May 13, 2008
Rainbow Links
EarthWeb.com
 
May 13, 2008
MySpace Profile Page Resources
HTML Goodies
 
May 13, 2008
How to Upload Your Photos onto the Web
HTML Goodies
 
May 13, 2008
Email Marketing for MySpace Artists
HTML Goodies
 
May 13, 2008
Top Online Marketing Techniques
HTML Goodies
 
May 13, 2008
I want to create a site just like ____, is that a violation of...
About
 
Courtesy of moreover.com
 
Want to receive new articles via e-mail? Click here!
/Home /PHP /Counters

Making a text file counter 

  Views:    3125
  Votes:    1
by Diego Botello 12/02/03 Rating: 

Synopsis:

This article will show you how to make a simple text file counter.
Pages: 
The Article

To make our text file counter we are going to make use of two files: counter.php and count.txt. The following is the code for the counter.php file. For it to work properly you will need to upload a count.txt file to your server previously and chmod it to 666. The text file must contain the number 1. Each time you refresh the counter.php page the count will increase in 1.

<?php

$file = fopen( "count.txt", 'r' );

while ( ! feof( $file ) )

{

$count = fgets( $file );

}

$count++;

print $count;

fclose( $file );

$file = fopen( "count.txt", "w" );

fwrite( $file, $count );

fclose( $file );

?>

 

Now lets explain the code above. To open a file for reading you need to use the fopen function and give it two arguments, the file name (count.txt), and the 'r' that represents that the file is being opened for reading. If you want to open a file for writing then you use 'w' and for append 'a'.

Now the next code chunk.

while ( ! feof( $file ) )

{

$count = fgets( $file);

}

This actually reads the file. It means that while our file has not reached the end of file ( ! feof) it should read the next line. To read a line you make use of the fgets function. It requires the name of the file been read ($file)

$count++;

print $count;

fclose( $file );

With the above we add 1 number to the count, print it and then close the file.

$file = fopen( "count.txt", "w" );

fwrite( $file, $count );

fclose( $file );

The above code open the file now for writting purposes. The second line uses the fwrite function to write to our count.txt file. This function needs the name of the file to be use ($file) and the value to enter it. In this case it was a variable but it also can be a string. Finally, to keep everything clean, we close the file.

Pages: 

Similar/related articles:


 
  Sponsors