How to make a cookie with PHP [duplicate]

自古美人都是妖i 提交于 2019-12-02 11:21:31

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!