Question

I got this simple hit counter off the internet and it's exactly what I needed:

<?PHP session_start();
    if(isset($_SESSION['views'])){
        $_SESSION['views']=$_SESSION['views']+1;
        }
        else{
        $_SESSION['views']=1;
        }
        echo "Total page views= ".$_SESSION['views'];
?>

So I threw it in my home.html which needless to say is my homepage. I however want the views to be printed on my info.html page, but I want it displaying the hits for home.html. Does anyone know if that's possible?

Was it helpful?

Solution

Firstly you need to change your pages to .php extensions not .html if you need PHP to be compiled by the server.

There are probably a few ways of achieving what you need, however i will first point out a few things about php sessions you should know.

  1. Session variables are available from any page on your site, providing a the session_start(); function is called first.

  2. Sessions are essentially temp storage. In a nutshell a cookie containing a unique id is saved to the users computer. The unique id is reference to the session information stored on the server (temporarily).

For full info check out php.net

Because sessions are temp storage and they are unique to a user, you will not be able to show any users visits to the home page made by other users except themselves. To achieve this you would need to create a solution which has global and perminent storage (i.e. DB or File).

Now I will show you the solution to what you have asked, i just wasnt sure of the context, so thought i would explain the constraints.

Ok, so you should include the code below on home.php.

<?php 
    session_start();
    if(isset($_SESSION['views'])){
        $_SESSION['views']++;
    } else{
        $_SESSION['views']=1;
    }
?>

This is exactly the same as what you had except i removed the echo function.

Now over on the info.php page add the following.

<?php 
    session_start();
    if(isset($_SESSION['views'])){
        echo $_SESSION['views'];
    }
?>

This will then display the amount of times the user has viewed home.php.

OTHER TIPS

Put this in your home.html

<?PHP session_start();
if(isset($_SESSION['views'])){
    $_SESSION['views']=$_SESSION['views']+1;
    }
    else{
    $_SESSION['views']=1;
    }

?>

and this on your info.html

<?PHP session_start();
if(isset($_SESSION['views'])){
    echo "Total page views= ".$_SESSION['views'];
} else {
    echo "no page views to show";
}

?>

But you realize that this only counts a single persons visits, sessions are per person (devise) not shared. And that person will only see his own count; until the session expires.

And you many need to home.html to home.php for this to work! or set html files to parse as php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top