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)

实例代码如下:

  1. makecookie('111','www.111cn.net');
  2. //清除cookie
  3. clearcookies();
  4. //下面兴一个支持二级域名cookie函数吧.
  5. function setcookielive($name, $value='', $expire=0, $path='', $domain='', $secure=false, $httponly=false) {
  6. //set a cookie as usual, but also add it to $_cookie so the current page load has access
  7. $_cookie[$name] = $value;
  8. return setcookie($name,$value,$expire,$path,$domain,$secure,$httponly);
  9. }
  10. //调用方法
  11. setcookielive('webab','111cn',time()+86000,'/','111cn.net');
  12. //一入门级cookie设置方法
  13. setcookie("cookie[three]", "cookiethree");
  14. setcookie("cookie[two]", "cookietwo");
  15. setcookie("cookie[one]", "cookieone");
  16. // after the page reloads, print them out
  17. if (isset($_cookie['cookie'])) {
  18. foreach ($_cookie['cookie'] as $name => $value) {
  19. echo "$name : $value <br />n";
  20. }
  21. }

js获取 cookie方法实例代码如下:

  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  4. <title>Insert title here</title>
  5. </head>
  6. <body>
  7. <script type="text/javascript">
  8. //get cookie
  9. function getCookie(name) {
  10. var nameEQ = name + "=";
  11. var ca = document.cookie.split(';');
  12. for(var i=0;i < ca.length;i++) {
  13. var c = ca[i];
  14. while (c.charAt(0)==' ') {
  15. c = c.substring(1,c.length);
  16. }
  17. if (c.indexOf(nameEQ) == 0) {
  18. return unescape(c.substring(nameEQ.length,c.length));
  19. }
  20. }
  21. return false;
  22. }
  23. //clear cookie
  24. function clearCookie(name) {
  25. setCookie(name, "", -1);
  26. }
  27. //set cookie
  28. function setCookie(name, value, seconds) {
  29. seconds = seconds || 0;
  30. var expires = "";
  31. if (seconds != 0 ) {
  32. var date = new Date();
  33. date.setTime(date.getTime()+(seconds*1000));
  34. expires = "; expires="+date.toGMTString();
  35. }
  36. document.cookie = name+"="+escape(value)+expires+"; path=/";
  37. }
  38. alert(getCookie('test2'));
  39. </script>
  40. </body>
  41. </html>