PHP与JavaScript下的Cookie操作

下面的例子列出几种情形交互场景,列出JS和php交互的方法。总结下,以免日后再为cookie问题困扰。

setcookie.php


getcookie.php

总结:

  1. php用自身函数读取php 的cookie,没有任何障碍,无需解码处理。
  2. js采用cookie.js方法读取js 的cookie,没有任何障碍,无需解码处理。
  3. js读取php的中文cookie,需要做 "decodeURIComponent (escape(php_cn_ck)) "函数处理
  4. php读取js的中文cookie 需要做 "unescape()" 函数处理

cookie.js

	var Cookies = {};
/**
* 设置Cookies
*/
Cookies.set = function(name, value){
var argv = arguments;
var argc = arguments.length;
var expires = (argc > 2) ? argv[2] : null;
if(expires != null){
var exp   = new Date();
exp.setTime(exp.getTime() + 8*3600 + expires);
}
alert(exp.toGMTString());
var path = (argc > 3) ? argv[3] : '/';
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + exp.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
};
/**
* 读取Cookies
*/
Cookies.get = function(name){
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
var j = 0;
while(i < clen){
j = i + alen;
if (document.cookie.substring(i, j) == arg)
return Cookies.getCookieVal(j);
i = document.cookie.indexOf(" ", i) + 1;
if(i == 0)
break;
}
return null;
};
/**
* 清除Cookies
*/
Cookies.clear = function(name) {
if(Cookies.get(name)){
var expdate = new Date();
expdate.setTime(expdate.getTime() - (86400 * 1000 * 1));
Cookies.set(name, "", expdate);
}
};
Cookies.getCookieVal = function(offset){
var endstr = document.cookie.indexOf(";", offset);
if(endstr == -1){
endstr = document.cookie.length;
}
return unescape(document.cookie.substring(offset, endstr));
};

4 function.php

  

参考:http://www.nowamagic.net/webdesign/webdesign_CookieInPhpJavascript.phpPHP与JavaScript下的Cookie操作

上一篇:java中静态代码块的用法 static用法详解和static静态导入


下一篇:Javascript中关于cookie的那些事儿