Page 343 - Beginning PHP 5.3
P. 343

Chapter 11: Working with Files and Directories
                             echo “<p>You’re visitor No. $counter.</p>”;

                             if ( !( $handle = fopen( $counterFile, “w” ) ) ){
                               die( “Cannot open the counter file for writing.” );
                             }

                             fwrite( $handle, $counter );
                             fclose( $handle );

                             ?>

                               </body>
                             </html>

                         Save this script as hit_counter.php and give it a try. Figure 11-1 shows a sample run.


















                                      Figure 11-1

                         To start with, you’ll see “You’re visitor No. 1.” If you now reload the page, you’ll see the counter
                         change to 2. Each time you reload, the counter increments by 1.
                         How It Works
                         After displaying a page header, the script stores the filename of the file that will hold the hit count:
                             $counterFile = “./count.dat“;

                         Next, the script checks to see if the counter file exists. If it doesn’t, it is created by opening the file for
                         writing, writing a zero to it (thereby initializing the hit count to zero), then closing it:

                             if ( !file_exists( $counterFile ) ) {
                               if ( !( $handle = fopen( $counterFile, “w” ) ) ) {
                                 die( “Cannot create the counter file.” );
                               } else {
                                 fwrite( $handle, 0 );
                                 fclose( $handle );
                               }
                             }




                                                                                                         305





                                                                                                      9/21/09   9:10:13 AM
          c11.indd   305
          c11.indd   305                                                                              9/21/09   9:10:13 AM
   338   339   340   341   342   343   344   345   346   347   348