Skip to content
Advertisement

how do I display “how many days ago a user visited a website” in PHP

I want to display how many days/hours/minutes/seconds ago a user last visited the website. I’m new to cookies and can’t get to make them work.

Edit: Right now $lastVisit and $thisVisit are the same, how would i make them separate?

Here’s my code so far (I know it’s doing nothing close to what it’s supposed to do):

<?php
    
    if(isset($_COOKIE['LastCookie']))
    {
        $lastVisit = $_COOKIE['LastCookie'];
        $inOneMonth = time() + (60*60*24*30);
        setcookie('LastCookie', time(), $inOneMonth);
        $thisVisit = $_COOKIE['LastCookie'];
?>
        <html>
            <head>
                <title>Cookie Exercise</title>
            </head>
            <body>
                <p> Your last visit was before: </br /></p>
                <?php 
                    echo $lastVisit."<br />"; 
                    $diff = $thisVisit - $lastVisit;
                    $seconds = $diff % 60;
                    $minutes = $seconds % 60;
                    $hours = $minutes % 60;
                    $days = $hours % 24;
                    echo "Diff: $diff <br /> $days $hours $minutes $seconds";
                ?>
            </body>
        </html>
<?php    
    }
    else 
    {
        setcookie('LastCookie', time(), time() + (60*60*24*30));
?>
        <html>
            <head>
                <title>Cookie Exercise</title>
            </head>
            <body>
                <p> This is your first visit to this website </br /></p>
                
            </body>
        </html>
<?php 
    }
 ?>

Here’s the exercise I’m trying to do incase my explaination wasn’t clear: 1

Advertisement

Answer

You have this condition:

if(isset($_COOKIE['LastCookie']))

As a prerequisite to this line of code:

setcookie('LastCookie', time(), $inOneMonth);

… so you only ever update an existing cookie. You never set a new one if this is the first visit.

You need to calculate $lastVisit if the cookie is set, but set the new cookie regardless (outside of the condition).

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement