setcookie() 函數向客戶端發送一個 HTTP cookie。
cookie 是由服務器發送到浏覽器的變量。cookie 通常是服務器嵌入到用戶計算機中的小文本文件。每當計算機通過浏覽器請求一個頁面,就會發送這個 cookie。
cookie 的名稱指定為相同名稱的變量。例如,如果被發送的 cookie 名為 "name",會自動創建名為 $user 的變量,包含 cookie 的值。
必須在任何其他輸出發送前對 cookie 進行賦值。
如果成功,則該函數返回 true,否則返回 false。
語法
setcookie(name,value,expire,path,domain,secure)
例
代碼如下 復制代碼makecookie('111','www.111cn.net');
//清除cookie
clearcookies();
//下面興一個支持二級域名cookie函數吧。
function setcookielive($name, $value='', $expire=0, $path='', $domain='', $secure=false, $httponly=false) {
//set a cookie as usual, but also add it to $_cookie so the current page load has access
$_cookie[$name] = $value;
return setcookie($name,$value,$expire,$path,$domain,$secure,$httponly);
}
//調用方法
setcookielive('webab','111cn',time()+86000,'/','111cn.net');
//一入門級cookie設置方法
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");
// after the page reloads, print them out
if (isset($_cookie['cookie'])) {
foreach ($_cookie['cookie'] as $name => $value) {
echo "$name : $value <br />n";
}
}
js獲取 cookie方法
代碼如下 復制代碼<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
//get cookie
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
return unescape(c.substring(nameEQ.length,c.length));
}
}
return false;
}
//clear cookie
function clearCookie(name) {
setCookie(name, "", -1);
}
//set cookie
function setCookie(name, value, seconds) {
seconds = seconds || 0;
var expires = "";
if (seconds != 0 ) {
var date = new Date();
date.setTime(date.getTime()+(seconds*1000));
expires = "; expires="+date.toGMTString();
}
document.cookie = name+"="+escape(value)+expires+"; path=/";
}
alert(getCookie('test2'));
</script>
</body>
</html>