Creating a Web Page Counter

Okay, let’s try something new. Now that you know about basic session variables, let’s create a web page counter. This counter will recognize how many times a visitor has visited your page and display the number on the screen. The counter starts at 0 when the page is closed.

Developing a counter requires just a little PHP. We will open a session and reference the counter (which creates the variable if it doesn’t exist, or increments it if it does exist). The following code fragment is taken from phpft13-04.php:

<?php
session_name("counter");
session_start();
header("Cache-control:private");

$_SESSION['counter']++;

echo "Hey, welcome to this web page. While you are here, feel free to browse
  some other sites. Just make sure you come back!. Hey, you might as well check
  out <a href="http://www.maneeshsethi.com"> ManeeshSethi.com </a> while you
  are here!";

echo "<p>We will keep a record of how many times you come back!";

echo "<p><p><div align="center">
You have visited our page {$_SESSION['counter']} times.";

?>

This is kind of strange, but all of the real power comes from this line:

$_SESSION['counter']++;

This line creates the counter variable if it does not exist, and it increments it by 1 using the ++ operator if it does exist. Then, we echo out the session counter at the bottom of the page. This tells the visitor how many times she has visited the site. When she leaves the page, the session remains open. If the user returns, the counter still increments correctly.

Let’s see what happens. First of all, you open the session, as shown in Figure 13.11.

Figure 13.11. The phpft13-04.php file.


Now we are going to navigate away from the PHP page. We might go to the indicated site (www.maneeshsethi.com). Figure 13.12 shows how the PHP page has disappeared and has been replaced with ManeeshSethi.com.

Now go back to the PHP file. We cannot just press the browser’s Back button, because we won’t rerun the PHP script that way. Instead, we are going to access the correct file using the address bar. Type in the PHP file’s location and check out the result in Figure 13.13. Check it out! The counter continues to update the number even if the page has been changed! In Figure 13.11, you see a 5, and after leaving and coming back, the counter says 6.

Figure 13.12. Navigating away from the PHP file.


Figure 13.13. Returning to phpft13-04.php.


If you want to keep the counter running even when the session ends, you could assign the value of the session variable to a cookie, and load the cookie every time the page runs. Why don’t you try doing that as an exercise? We will come back to that program at the end of the chapter and create a running counter that tracks the visitor at all times. For right now, we are going to create a log-in page.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.81.206