How can a save a cookie using php for every visitor on my site? My website also has a unique ID generator. I want to know how to make the id stay the same using cookies
Asked
Active
Viewed 1,143 times
2 Answers
8
You can use the setcookie() function to store a cookie.
Example Code
//Check if cookie exists
if (isset($_COOKIE['uid'])) {
//Get UID from cookie
$uid = $_COOKIE['uid'];
} else {
//Generate UID
$uid = uniqid();
//Store in cookie
setcookie('uid',$uid);
}

fin1te
- 4,289
- 1
- 19
- 16
-
I have been looking into this as well. The problem with uniqid is that it is possible that you will have a duplicate, so it is not safe if you want to use it as an identifier – Thomas Williams Feb 27 '17 at 11:45
-1
You could check W3Schools' PHP guide, it has a lot of useful code snippets to do with cookies.
Depending what you are doing, you may also want to check out Sessions.

Ed Holloway-George
- 5,092
- 2
- 37
- 66
-
1-1: http://w3fools.com/ Referring to the PHP Manual would be a better reference as there are tons of examples on the manual and the manual is generally up to date and correct. – Jim Apr 21 '11 at 15:42
-
My apologies, retrospectively thinking i'd have too agree. I was just speaking from experience that I used w3schools when dealing with cookies. – Ed Holloway-George Apr 21 '11 at 23:09
-
Gotcha :) If you edit it, I will remove the downvote (just add a period or something.) – Jim Apr 22 '11 at 03:39