include "counter_func.php" ?>
This is an example on how to use a PHP function that updates data inside a text file. The function stores the number of times a page has been display.
The PHP function is not placed inside the HTML file, it is placed in a seperate file so that it may be used from several other HTML pages.
Example:
This page has been visited echo getCounter("1"); ?> times since the dawn of time.
Click the browser's Refresh button to increase the value.
To be able to use the counter function in several pages we have put this function in a separate file named counter_func.php. We use the PHP include command to make it accessible in this page:
<? include "counter_func.php" ?>
The statement above is placed in the head section of the page. This makes it possible to use the counter function in PHP code that comes after the include statement.
To display the counter in the page (and increase the count) we insert the following PHP command in the HTML section:
<? echo getCounter("1"); ?>
TIP: The value "1" inside the brackets in the statement getCounter("1") is a value (a parameter) that you choose to identify a specific counter for a page or a collection of pages. The value can either be a number or a short text string. This makes it possible to handle several different counters using the same function.
You may for example use the call getCounter("index"); when it is called from your index page and use the call getCounter("info"); when it is called from your information page.
Below is the getCounter() function in the file counter_func.php that performs this magic:
<? function getCounter($counterID)
{
// each counter value is stored inside a unique file
// We use $counterID as a part of the file name
// Example: file name will be "counter1.txt" if $counterID is set to "1"
$fileName = "counter".$counterID.".txt";
if( file_exists($fileName) ) {
list($numVisitors)=file($fileName); // Read contents from the file
} else {
$numVisitors=0; // This is the first time the page is accessed
}
$numVisitors=$numVisitors+1; // Increase the count
$fil=fopen($fileName,"w"); // Open the file to replace old value
fputs($fil,$numVisitors); // Write the new count to the file
fclose($fil); // Close the file
return $numVisitors; // Return the new count
}
?>
This PHP code example is copyright © 2002-2003 Optima System. All rights reserved worldwide. Unauthorized distribution prohibited. SpinPHP™ User License.