In order to open a file in php, we need to call the function fopen(). This will open the file, if it exists, and return a file pointer. Don't worry too much on what a file pointer is, think of it as an alias for the file. Instead of using the file name, you pass a file pointer to functions. Here is the beginning of our code:
function count_hit()
{
$file_pointer= fopen("hits.txt", "r+");
r | Open the file for reading, place the file pointer at the beginning of the file. |
w | Open the file for writing, place the file pointer at the beginning of the file, create the file if it doesn't exist, and set the file to zero length. |
w+ | Open the file for reading and writing, place the file pointer at the beginning of the file, create the file if it doesn't exist, and set the file to zero length. |
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. |
b | Open the file in binary mode, if not needed, this will be ignored. |
fopen() can take one more parameter: 1. If you pass the third parameter as 1, the file you passed the name of in the first parameter will be searched for in the include path. The include path is specified when php if first installed on the server, most of the time you won't have control over it. We store the result of fopen() in a variable named $file_pointer. If the file does not exist, fopen() will return false; we need to test for that.
if ($file_pointer == false) { return "Error: could not open the file! It may not exist!"; exit; }
Now that the file is open, we need to read from it, to do that we use the fread() function.
$hits= fread($file_pointer, filesize("hits.txt"));
$hits= trim($hits);
$hits++; fseek($file_pointer, 0); $result= fwrite($file_pointer, $hits); if ($result == false) { return "Error: could not write to the file!"; exit; } else { return $hits; }
Only one more thing left to do: close the file. To do that we use fclose() and pass it the file pointer, oh and can't forget the error checking =)
$close= fclose($file_pointer); if ($close == false) { return "Error: could not close the file!"; exit; }
function count_hit() { $file_pointer= fopen("hits.txt", "r+"); if ($file_pointer == false) { return "Error: could not open the file! It may not exist!"; exit; } $hits= fread($file_pointer, filesize("hits.txt")); $hits= trim($hits); $hits++; fseek($file_pointer, 0); $result= fwrite($file_pointer, $hits); if ($result == false) { return "Error: could not write to the file!"; exit; } else { return $hits; } $close= fclose($file_pointer); if ($close == false) { echo "Error: could not close the file!"; exit; } } ?>
its working gr8......
ReplyDelete