怎样使用php与jquery设置和读取cookies


Posted in PHP onAugust 08, 2013

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一样传递到页面,很容易被不法份子截取到。
但是,只要有适当的预防措施,你就可以用这个简单的技术实现大量的互动。
PHP 相关文章推荐
php5编程中的异常处理详细方法介绍
Jul 29 PHP
PHP similar_text 字符串的相似性比较函数
May 26 PHP
通过table标签,PHP输出EXCEL的实现方法
Jul 24 PHP
php中ob函数缓冲机制深入理解
Aug 03 PHP
PHP微信支付开发实例
Jun 22 PHP
Laravel搭建后台登录系统步骤详解
Jul 26 PHP
PHP简单检测网址是否能够正常打开的方法
Sep 04 PHP
PHP房贷计算器实例代码,等额本息,等额本金
Apr 01 PHP
PHP实现的数独求解问题示例
Apr 18 PHP
ThinkPHP 3.2.2实现事务操作的方法
May 05 PHP
php对微信支付回调处理的方法
Aug 23 PHP
PhpStorm连接服务器并实现自动上传功能
Dec 09 PHP
如何取得中文字符串中出现次数最多的子串
Aug 08 #PHP
php读取图片内容并输出到浏览器的实现代码
Aug 08 #PHP
php调用Google translate_tts api实现代码
Aug 07 #PHP
利用php+mcDropdown实现文件路径可在下拉框选择
Aug 07 #PHP
PHP生成验证码时“图像因其本身有错无法显示”的解决方法
Aug 07 #PHP
对于PHP 5.4 你必须要知道的
Aug 07 #PHP
php缓存技术详细总结
Aug 07 #PHP
You might like
解析phpstorm + xdebug 远程断点调试
2013/06/20 PHP
ThinkPHP空模块和空操作详解
2014/06/30 PHP
再Docker中架设完整的WordPress站点全攻略
2015/07/29 PHP
php+html5实现无刷新图片上传教程
2016/01/22 PHP
javascript encodeURI和encodeURIComponent的比较
2010/04/03 Javascript
利用google提供的API(JavaScript接口)获取网站访问者IP地理位置的代码详解
2010/07/24 Javascript
jQuery下的动画处理总结
2013/10/10 Javascript
JS实现点击按钮自动增加一个单元格的方法
2015/03/09 Javascript
原生JavaScript实现异步多文件上传
2015/12/02 Javascript
教你如何在Node.js中使用jQuery
2016/08/28 Javascript
轻松实现js弹框显示选项
2016/09/13 Javascript
jQuery 获取遍历获取table中每一个tr中的第一个td的方法
2016/10/05 Javascript
JavaScript实现星星等级评价功能
2017/03/22 Javascript
详解微信小程序开发之formId使用(模板消息)
2019/08/27 Javascript
React+EggJs实现断点续传的示例代码
2020/07/07 Javascript
Vue实现点击导航栏当前标签后变色功能
2020/08/19 Javascript
python模块restful使用方法实例
2013/12/10 Python
python字符串连接的N种方式总结
2014/09/17 Python
python实现根据用户输入从电影网站获取影片信息的方法
2015/04/07 Python
node.js获取参数的常用方法(总结)
2017/05/29 Python
100行python代码实现跳一跳辅助程序
2018/01/15 Python
深入浅析Python2.x和3.x版本的主要区别
2018/11/30 Python
python reverse反转部分数组的实例
2018/12/13 Python
解决Python中报错TypeError: must be str, not bytes问题
2020/04/07 Python
matplotlib bar()实现多组数据并列柱状图通用简便创建方法
2021/02/24 Python
Dockers美国官方网站:卡其裤、男士服装、鞋及配件
2016/11/22 全球购物
100%植物性、有机、即食餐:Sakara Life
2018/10/25 全球购物
eBay英国购物网站:eBay.co.uk
2019/06/19 全球购物
世嘉游戏英国官方商店:SEGA Shop UK
2019/09/20 全球购物
应届生自荐信范文
2014/02/21 职场文书
投标承诺函范文
2015/01/21 职场文书
团队拓展训练感想
2015/08/07 职场文书
初中语文教师研修日志
2015/11/13 职场文书
使用Html+Css实现简易导航栏功能(导航栏遇到鼠标切换背景颜色)
2021/04/07 HTML / CSS
pd.DataFrame中的几种索引变换的实现
2022/06/16 Python
Windows Server 2016服务器用户管理及远程授权图文教程
2022/08/14 Servers