Reputation: 2870
I have written a PHP script which takes information about visitors IP and browser from a website and stores it in a table in my database. This script is included in the header and runs every time each page is loaded, google analytics type thing. survey.php
I want this code to run only for each new visitor of the website, so that I only log each new visitor.
I guess this is done by setting a cookie so I wrote this other code to set a cookie and then include the survey.php only when there is no cookie. I've used the ! function in isset to run the if statement if it isn't present but it is not setting the cookie and is running the script upon each load.
Based on what it says in the manual I can't see where I am going wrong.
<?php
if(!isset($_COOKIE['Name'])){
setcookie("Name");
include ('survey.php');
}
?>
EDIT: I have added a value, tested it with multiple users, and the script still runs each load. No idea why.
Upvotes: 1
Views: 922
Reputation: 2870
RESOLVED
I was including the code as the first piece of code but not on the first line.
A code to set cookies has to begin before everything, on line 1.
Posting this so others can benefit.
Upvotes: 1
Reputation: 20853
Give your cookie a value:
$value = 'something from somewhere';
if(!isset($_COOKIE['Name'])){
setcookie("Name", $value);
include ('survey.php');
}
Given that it's to identify new users, using a '0' or '1' would be sufficient.
If you want the cookie to expire at a future point:
setcookie("Name", $value, time()+604800); /* expires in a week */
EDIT:
I've tried this with the following code in a simple page:
<?php
if(!isset($_COOKIE['Test'])){
setcookie("Test", '1');
echo "Cookie set";
//include ('survey.php');
}
?>
I get "Cookie set" once and then don't see it again on subsequent refreshes. I can also see the cookie in the console:
Test | 1 | www.domain.com | / | Session | 5
The only potential issue (as you're using different users) is that this cookie is set for the current session here, so setting it's expiry far in the future would be good for permanence and would prevent your users from seeing your survey anytime soon:
<?php
if(!isset($_COOKIE['Test'])){
//Expires on 31 december 2015
setcookie("Name","1",mktime (0, 0, 0, 12, 31, 2015));
include ('survey.php');
}
?>
Upvotes: 2
Reputation: 19672
In order to set a cookie, or rather, to get the cookie sent to the user from PHP, you'll need to give it a value. Browsers (at least most modern ones) take an empty cookie header as an order to clear whatever cookie they had with that name.
So, obviously, it won't be sent on further requests, as browsers, instead of setting it to null, discarded it.
Give it a random, short value and all your problems will go away:
setcookie("Name",rand(1,10));
or similar.
Upvotes: 1
Reputation: 56
1) Try to set value for cookie like this $value = 'Test'; setcookie("TestCookie", $value);
2) check whether cookies enabled in browser
Upvotes: 1