Possible Duplicate:
How to set cookies for uuid
Hello, I would like to know how to make a cookie in PHP. I have researched the topic for a couple of hours already, yet im a newbie to PHP and dont understand it that much. I have found this script, but dont know how to implant it into my website, can anyone help?
setcookie(name, value, expire, path, domain);
What do you want to do with your cookie? If you want to track information on the server from request-to-request, you probably want to use a session, which automatically uses cookies.
Otherwise, go ahead and use setcookie
for cookies that your application needs for other functionality. Pay attention to this snippet from the PHP manual:
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.
<?php setcookie("cookiename", uniqid()); ?>
make sure you put it before anything is output to the page (like you do with headers)
so:
<?php
//fill in with the info you want
$name = 'theCookie';
$value = 'tasty';
$expire = null;
$path = '/';
$domain = null;
setcookie($name, $value, $expire, $path, $domain);
...rest of code
?>
Here is a basic example
<? setcookie("foobar", "Hello, world!", -1) ?>
This will create a cookie named "foobar" with the value of "Hello, world!", and will expire when the browser closes.
Also, make sure you set cookies before any HTML output otherwise it won't be created.
To check it's value, do on a following page.
<? echo $_COOKIE['foobar']; ?>
You have the answer.
<?php
setcookie("TestCookie", "myValue", time()+3600, "/~rasmus/", ".example.com", 1);
?>
This creates a cookie called TestCookie with a value of "myValue", it will expire 1 hour from its creation. The website/domain is example.com and the folder path you're in is /~rasmus/.
More information on setcookie here: http://php.net/manual/en/function.setcookie.php
来源:https://stackoverflow.com/questions/5748582/how-to-make-a-cookie-with-php