Hi. I'm trying to create a cookie where the name is the username that a user submits through a form and the value is the number of their visits. I can't get the number of visits to increment. Any ideas why this is not working? Heres my code:

<?php
$Username = "";
$visits = 1;

$Username = $_GET['username'];

if (isset($_GET['username']) &&
     isset($_GET['submit'])) {
   
if (isset($_COOKIE['$Username']))
    $visits = $_COOKIE['$Username'];

$vists = $visits + 1;
setcookie("$Username", "$visits", time()+60*60*24);
	
if (isset($_COOKIE['$Username']))
	$visits = $_COOKIE['$Username']; // get the current number of visits associated with this user name (using $_COOKIE)
	$visits = $_COOKIE['$Username'] + 1; // add 1 to the number
	setcookie("$Username", "$visits", time()+60*60*24); // use setcookie() to write the new cookie
	echo "<p>Welcome, $Username. This is visit # $visits !</p>";

}
?>

Recommended Answers

All 2 Replies

if (isset($_COOKIE['$Username']))
    $visits = $_COOKIE['$Username'];

Never works because variables in single quotes ', aren't parsed. You need double quotes, ie.,

if (isset($_COOKIE["$Username"]))
    $visits = $_COOKIE["$Username"];

You have to do that for all of those variables in there.

Thank you, that worked!

I found out it also works without the double quotes. ($visits = $_COOKIE[$Username];)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.