| paris.us
............Views...96Home Page
........Comment(Login First)
|
This PHP code will increment and display a View Count everytime a user views the web page that contains this counter <?php $filename = 'xxviewcount.txt'; // 1. Check if the file exists. If not, initialize it with 0. if (!file_exists($filename)) { file_put_contents($filename, '0'); } // 2. Open the file for reading and writing $file = fopen($filename, 'c+'); if ($file) { // Acquire an exclusive lock (prevents data corruption from simultaneous hits) if (flock($file, LOCK_EX)) { // 3. Read the current count (forcing it to an integer for safety) $current_count = (int)trim(fread($file, filesize($filename) ? filesize($filename) : 1)); // 4. Display the current count to the user echo "This page has been viewed " . $current_count . " times."; // 5. Increment the count $new_count = $current_count + 1; // 6. Rewind the file pointer to the beginning and truncate the file ftruncate($file, 0); rewind($file); // 7. Save the new count fwrite($file, $new_count); // Flush output before releasing the lock fflush($file); // 8. Release the lock flock($file, LOCK_UN); } else { echo "Error: Could not lock the file for writing."; } // Close the file connection fclose($file); } else { echo "Error: Could not open the counter file."; } ?> |
0 Comments |