Lets start by using the file_exists() function to check if the counter.dat file exists. If it does then we are going to open it using the fopen() function.
Code: Select all
if(file_exists("counter.dat"))
{
$exist_file = fopen("counter.dat", "r");
Now we are going to use the fgets() function in order to find out how many hits are in the counter.dat file. We are going to save the command we use to find the hits into a variable (we'll call it new_count), this way we can access it later on.
Code: Select all
$new_count = fgets($exist_file, 255);
Code: Select all
$new_count++;
fclose($exist_file);
Code: Select all
print("$new_count people have visited this page");
Code: Select all
$exist_count = fopen("counter.dat", "w");
fputs($exist_count, $new_count);
fclose($exist_count);
Now we are going to close the if section and work on the else section. Incase the counter.dat file doesn't exist we are going to let PHP create it for us. To do this we use the following code:
Code: Select all
}
else
{
$new_file = fopen("counter.dat", "w");
fputs($new_file, "1");
print("1 person have visited this page");
fclose($new_file);
}
Code: Select all
<?
if(file_exists("counter.dat"))
{
$exist_file = fopen("counter.dat", "r");
$new_count = fgets($exist_file, 255);
$new_count++;
fclose($exist_file);
print("$new_count people have visited this page");
$exist_count = fopen("counter.dat", "w");
fputs($exist_count, $new_count);
fclose($exist_count);
}
else
{
$new_file = fopen("counter.dat", "w");
fputs($new_file, "1");
print("1 person have visited this page");
fclose($new_file);
}
?>
--------------------------------------------------------------------------------
Now as promised lets quickly cover all of the options that you can place when using the fopen() function. Quoting from the PHP Manual:
'r' - Open for reading only; place the file pointer at the beginning of the file.
'r+' - Open for reading and writing; place the file pointer at the beginning of the file.
'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.