Home  >  Article  >  php教程  >  PHP setcookie()函数用法介绍

PHP setcookie()函数用法介绍

WBOY
WBOYOriginal
2016-06-13 10:15:381063browse

cookie就像是php中的session一样,只是一个在客户端一个是在服务器端了,下面我来详细介绍php中setcookie对cookie设置与删除代码。

setcookie()语法

setcookie (PHP 3, PHP 4, PHP 5)

setcookie -- 发送一个 cookie 信息

说明:bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure]]]]] )

写cookie

 代码如下 复制代码

$value = 'something from somewhere';

setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600);  /* expire in 1 hour */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1);
?>

读cookie

 代码如下 复制代码

// Print an individual cookie
echo $_COOKIE["TestCookie"];
echo $HTTP_COOKIE_VARS["TestCookie"];

// Another way to debug/test is to view all cookies
print_r($_COOKIE);
?>


删除cookie

 代码如下 复制代码

// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);
?>


由于cookie与HTTP的特定方式,你必须在你输出任何文本前,传送出所有的cookie。否则PHP会给出警告,并且cookie也不会被传送。因此,这样做是正确的:

 代码如下 复制代码

setcookie(’name’, ‘jeff’);

echo “Hello Everyone!”;

?>

以下是错误地:

 代码如下 复制代码

echo “Hello Everyone!”;

setcookie(’name’, ‘jeff’);

?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn