phpwebcounterhit

Display output of PHP on another page


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?


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.