php中setcookie() 函数用法介绍
setcookie() 函数是php中一个用来设置cookie值的一个函数,下面我来总结一下setcookie() 函数的具体用法以及设置之后怎么获取cookie的值.
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>