Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using cookies to display number of times user has visited website in PHP

Tags:

html

php

So I'm fairly new to PHP and I've written up my first code to basically create two cookies to track the time the user last opened the website and a counter.

I want my website to display the time the person last opened up the website, with a counter saying "it's the $cookieValue you've visited us!".

    <!DOCTYPE html>
<?php
    $cookieValue = 1;

    setcookie("time", $cookieValue, time()+(86400*365));

    $cookieLastVisit = null;

    setcookie("lastVisit", $cookieLastVisit, time()+(86400*365));
    ?>
<html>
<head>
<title>Question 2</title>
</head>
<body>
<?php
    if (!isset($_COOKIE["time"])){
        echo ("Welcome to my webpage! It is the first time that you are here.");

        $visit = date(DATE_RFC1036);
        setcookie("lastVisit", $visit);
    }
    else {
        $cookieValue = ++$_COOKIE["time"];

        echo("Hello, this is the " . $cookieValue . " time that you are visiting my webpage. Last time you visited my webpage on: " . $cookieLastVisit);

        $visit = date(DATE_RFC1036);
        setcookie("lastVisit", $visit);
    }
    ?>
</body>
</html>

I've finished my code but can't grasp why when I open my website, absolutely nothing happens.

like image 848
lesterpierson123 Avatar asked Dec 03 '25 10:12

lesterpierson123


1 Answers

You will need to put all setcookie() function calls at the top of the page, before any output is sent to the browser.

like image 112
Aeron R Avatar answered Dec 04 '25 23:12

Aeron R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!