怎样使用php与jquery设置和读取cookies
http协议是一种无状态协议,这意味着你对网站的每一个请求都是独立的,而且因此无法通过它自身保存数据。但这种简单性也是它在互联网早期就广泛传播的原因之一。
不过,它仍然有一种方法能让你用cookies的形式来保存请求之间的信息。这种方法使你能够更有效率的进行会话管理和维持数据。
有两种处理cookies的方式—服务端(php,asp等)和客户端(javascript).在这个教程中,我们将学习到以php和javascript这两种方式如何去创建cookies。
cookies and php
setting cookies
在php中创建cookie你需要用到setcookie这个方法。它需要些参数(除了第一个参数是必需的,其它参数都是可选的)
setcookie(
'pagevisits', //cookie名字,必需的
$visited, //cookie的值
time()+7*24*60*60, //过期时间,设置为一个星期
'/', //cookie可用的文件路径
'demo.tutorialzine.com' //cookie绑定的域名
)
如果过期时间设置为0(默认设置也是0),那么当浏览器重启时cookie将会丢失。
参数'/'表示你域名下所有文件路径cookie都可以用(当然你也可以为它设置单一的文件路径,例:'/admin/')。
你还可以传给个这个函数别两个额外的参数,这里没有给出。它们被规定为boolean类型的。
第一个参数表示cookie仅在一个安全的https连接才运转,而第二个参数表示不能使用javascript操作cookie。
对大多数人来说,你只需要第四个参数,剩下的就忽略了。
reading cookies
用php读取cookie就简单多了。所有的传给脚本的cookies都在$_cookie这个超级全局数组里。
在我们的例子里,可以用下面的代码来读取cookies:
$visits = (int)$_cookie['pagevisits']+1;
echo "you visited this site: ".$visits." times";
值得注意的地方是,当下一个页面加载好时,也可以用$_cookie来取得你用setcookie方法设置的cookies,
你应该意识到了什么。
deleting cookies
为了删除cookies,仅仅需要用setcookie函数为cookies设置一个已经过去时间做为过期就行了。
setcookie(
'pagevisits',
$visited,
time()-7*24*60*60, //设置为前一个星期,cookie将会被删除
'/',
'demo.tutorialzine.com'
)
cookies and jquery
在jquery中使用cookies,你需要一个插件cookie plugin.
setting cookies
用cookie plug-in设置cookies是很直观的:
$(document).ready(function(){
// setting a kittens cookie, it will be lost on browser restart:
$.cookie("kittens","seven kittens");
// setting democookie (as seen in the demonstration):
$.cookie("democookie",text,{expires: 7, path: '/', domain: 'demo.tutorialzine.com'});
// "text" is a variable holding the string to be saved
});
reading cookies
读取cookie甚至更简单,只需要调用$.cookie()方法,给它一个cookie-name就可以了,这个方法会返回cookie的值:
$(document).ready(function(){
// getting the kittens cookie:
var str = $.cookie("kittens");
// str now contains "seven kittens"
});
deleting cookies
删除cookie,只需要在次使得$.cookie()方法,把第二个参数设置为null就可以了。
$(document).ready(function(){
// deleting the kittens cookie:
var str = $.cookie("kittens",null);
// no more kittens
});
完整例子:
demo.php
<?php
// always set cookies before any data or html are printed to the page
$visited = (int)$_cookie['pagevisits'] + 1;
setcookie( 'pagevisits', // name of the cookie, required
$visited, // the value of the cookie
time()+7*24*60*60, // expiration time, set for a week in the future
'/', // folder path, the cookie will be available for all scripts in every folder of the site
'demo.tutorialzine.com'); // domain to which the cookie will be locked
?>
<!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>microtut: getting and setting cookies with jquery & php | tutorialzine demo</title>
<link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css" />
<mce:script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" mce_src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></mce:script>
<mce:script type="text/javascript" src="jquery.cookie.js" mce_src="jquery.cookie.js"></mce:script>
<mce:script type="text/javascript"><!--
$(document).ready(function(){
var cookie = $.cookie('democookie');
// if the cookie has been set in a previous page load, show it in the div directly:
if(cookie) $('.jq-text').text(cookie).show();
$('.fields a').click(function(e){
var text = $('#inputbox').val();
// setting a cookie with a seven day validity:
$.cookie('democookie',text,{expires: 7, path: '/', domain: 'demo.tutorialzine.com'});
$('.jq-text').text(text).slidedown('slow');
e.preventdefault();
});
$('#form1').submit(function(e){ e.preventdefault(); })
})
// --></mce:script>
</head>
<body>
<h1>microtut: getting and setting cookies with jquery & php</h1>
<h2>go back <a href="http://tutorialzine.com/2010/03/microtut-getting-setting-cookies-jquery-php/" mce_href="http://tutorialzine.com/2010/03/microtut-getting-setting-cookies-jquery-php/">to the tutorial »</a></h2>
<div class="section">
<div class="counter"><?php echo $visited?></div>
<p>the number above indicates how many times you've visited this page (php cookie). reload to test.</p>
</div>
<div class="section">
<div class="jq-text"></div>
<form action="" method="get" id="form1">
<div class="fields">
<input type="text" id="inputbox" />
<a href="">save</a>
</div>
</form>
<p>write some text in the field above and click save. it will be saved between page reloads with a jquery cookie.</p>
</div>
</body>
</html>
jquery.cookie.js
/**
* cookie plugin
*
* copyright (c) 2006 klaus hartl (stilbuero.de)
* dual licensed under the mit and gpl licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
/**
* create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc delete a cookie by passing null as value. keep in mind that you have to use the same path and domain
* used when the cookie was set.
*
* @param string name the name of the cookie.
* @param string value the value of the cookie.
* @param object options an object literal containing key/value pairs to provide optional cookie attributes.
* @option number|date expires either an integer specifying the expiration date from now on in days or a date object.
* if a negative value is specified (e.g. a date in the past), the cookie will be deleted.
* if set to null or omitted, the cookie will be a session cookie and will not be retained
* when the the browser exits.
* @option string path the value of the path atribute of the cookie (default: path of page that created the cookie).
* @option string domain the value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option boolean secure if true, the secure attribute of the cookie will be set and the cookie transmission will
* require a secure protocol (like https).
* @type undefined
*
* @name $.cookie
* @cat plugins/cookie
* @author klaus hartl/klaus.hartl@stilbuero.de
*/
/**
* get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc get the value of a cookie.
*
* @param string name the name of the cookie.
* @return the value of the cookie.
* @type string
*
* @name $.cookie
* @cat plugins/cookie
* @author klaus hartl/klaus.hartl@stilbuero.de
*/
jquery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toutcstring)) {
var date;
if (typeof options.expires == 'number') {
date = new date();
date.settime(date.gettime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toutcstring(); // use expires attribute, max-age is not supported by ie
}
// caution: needed to parenthesize options.path and options.domain
// in the following expressions, otherwise they evaluate to undefined
// in the packed version for some reason...
var path = options.path ? '; path=' + (options.path) : '';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeuricomponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
var cookievalue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jquery.trim(cookies[i]);
// does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookievalue = decodeuricomponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookievalue;
}
};
styles.css
*{
margin:0;
padding:0;
}
body{
/* setting default text color, background and a font stack */
color:#555555;
font-size:0.825em;
background: #fcfcfc;
font-family:arial, helvetica, sans-serif;
}
.section{
margin:0 auto 60px;
text-align:center;
width:600px;
}
.counter{
color:#79cef1;
font-size:180px;
}
.jq-text{
display:none;
color:#79cef1;
font-size:80px;
}
p{
font-size:11px;
padding:0 200px;
}
form{
margin-bottom:15px;
}
input[type=text]{
border:1px solid #bbbbbb;
color:#444444;
font-family:arial,verdana,helvetica,sans-serif;
font-size:14px;
letter-spacing:1px;
padding:2px 4px;
}
/* the styles below are only necessary for the styling of the demo page: */
h1{
background:#f4f4f4;
border-bottom:1px solid #eeeeee;
font-size:20px;
font-weight:normal;
margin-bottom:15px;
padding:15px;
text-align:center;
}
h2 {
font-size:12px;
font-weight:normal;
padding-right:40px;
position:relative;
right:0;
text-align:right;
text-transform:uppercase;
top:-48px;
}
a, a:visited {
color:#0196e3;
text-decoration:none;
outline:none;
}
a:hover{
text-decoration:underline;
}
.clear{
clear:both;
}
h1,h2,p.tutinfo{
font-family:"myriad pro",arial,helvetica,sans-serif;
}
结束语:
关于cookie的使用,你需要注意的是不要把一些敏感信息(例如用户名、密码)保存在cookies中,
为因当每一个页面加载时cookies都会和headers一样传递到页面,很容易被不法份子截取到。
但是,只要有适当的预防措施,你就可以用这个简单的技术实现大量的互动。
上一篇: linux截屏命令import使用介绍
下一篇: 分割GBK中文遭遇乱码的解决方法
推荐阅读
-
怎样使用php与jquery设置和读取cookies
-
C#_Excel数据读取与写入_自定义解析封装类_支持设置标题行位置&使用excel表达式收集数据&单元格映射&标题映射&模板文件的参数数据替换(第二版-增加深度读取和更新功能)
-
怎样使用php与jquery设置和读取cookies
-
怎样使用php与jquery设置和读取cookies
-
ECharts地图应用:使用jQuery和PHP、MySQL异步读取数据
-
怎样使用php与jquery设置和读取cookies_PHP教程
-
怎样使用php与jquery设置和读取cookies_PHP教程
-
ECharts地图应用:使用jQuery和PHP、MySQL异步读取数据
-
C#_Excel数据读取与写入_自定义解析封装类_支持设置标题行位置&使用excel表达式收集数据&单元格映射&标题映射&模板文件的参数数据替换(第二版-增加深度读取和更新功能)
-
怎样使用php与jquery设置和读取cookies_PHP