File Input/Output Basics

Summary

Website statistics are maintained by system administrators to provide data about the users visiting their site as well as overall usage of the site. Website statistics can be collected in a variety of ways including: server log files, session IDs, cookies, and special PHP scripts.

In this lab we will create a simple PHP script to count the views of a web page, record that count to a file, and then display it. As a bonus, there is a section on how to create and use a simple cookie.

The instructions on this page will show you how to:

Create a simple PHP web counter

  1. We will create the simple PHP web counter script. Using pico or your favorite editor, create a PHP file called counter.php.

    <?php
    
    $fp = fopen("counter.txt", "r");
    $count = fread($fp, 1024);
    fclose($fp);
    $count = $count + 1;
    $fp = fopen("counter.txt", "w");
    fwrite($fp, $count);
    fclose($fp);
    
    ?>
    

    This code uses the built-in PHP functions fopen, fread, fwrite, fclose to open a file on disk called counter.txt, read in the file, write the current count to the file, and close the file.

  2. Using pico or your favorite editor, create and empty file called counter.txt. This file should be in the same directory as your counter.php file.

  3. To use your simple counter add the following line to one of your web pages, for example your site's home page: index.php

    <script type='text/javascript' src='counter.php'></script>
    

    This is a javascript command that loads the counter.php when the web page is loaded by a browser.

  4. If I were to add it to my index.php it might look like this:
    <?php
    
    // Include the layout file
    include './layout.php';
    
    // Use the myheader function from layout.php
    myheader("Geneaology World");
    
    // Add some body content here
    printf("<script type='text/javascript' src='counter.php'></script>");
    printf("<p>Suzi's Geaneology World is a member's only site for the geneaology
    addicted!  Enter here to learn more about the process of geanology as well
    get the latest news from important sources.</p>");
    
    // use the myfooter function from layout.php
    myfooter();
    ?>
    
  5. Instead of logging the data to a file, you can also update a record in your MySQL database.

Create simple cookie

Supose we want to track information about every visit a member makes to our site. We might create a cookie to store their preferences on their local hard disk, so that every time they come back we can display the proper pages.

  1. Use pico to create a PHP file called cookiedemo.php.
  2. Add an simple form input box so that the user can enter their name.
    <html>
      <head><title>Simple Cookie Demo</title></head>
      <body>
    
    <h2>Simple Cookie Demo</h2>
    
    <p>Enter your name and the web site will remember you next time.</p>
    
    <html>
      <head><title>Cookie Demo</title></head>
      <body>
    
    <form method="post" action="<?=$_SERVER['PHP_SELF']?>" >
    Enter your name: <input type="text" name="name" />
    What is your favorite color? <input type="text" name="color" />
    <input type="submit" value="Set Cookie" />
    </form>
    
      </body>
    </html>
    

    This form allows the user to enter some text into the input box and calls itself as an action. It uses the POST method.
  3. Next we will add the code for creating the cookie. Remember that cookies have to be created before any HTML is sent.

    <?php
    
    // Check if cookie is set
    if (!isset($_COOKIE['cookie_info'])) {
      if ($_POST && $_POST['name'] != "") {
        $time = time();
        $name = $_POST['name'];
        $color = $_POST['color'];
    
        // Set the cookie
        $cookie_data = $name . '- ' . $color;
        if (setcookie("cookie_info", $cookie_data, $time+3600) == TRUE) {
        }
      }
    
    ?>
    
  4. Finally, add a check to the bottom of your script, to display the cookie data if it exists.

    <?php
    } else {
    
    // Cookie is set and display cookie data
    $cookie_info = explode("-", $_COOKIE['cookie_info']); // Extract the data
    $name = $cookie_info[0];
    $color = $cookie_info[1];
    
    echo "Welcome back $name.  You like the color $color";
    echo "<br /><a href='destroycookie.php'>Click here to destroy the cookie</a>";
    }
    ?>
    

  5. Now we'll create a PHP script that will destroy the cookie.

    <?php
    
    $time= time();
    if (isset($_COOKIE['cookie_info'])) {
      setcookie("cookie_info", "", $time - 3600);
      echo "Cookie Destroyed";
    } else {
      echo "Cookie not set!";
    }
    
    
    ?>
    

Resources