程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> 怎樣使用php與jquery設置和讀取cookies

怎樣使用php與jquery設置和讀取cookies

編輯:PHP綜合

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/[email protected]
 */
/**
 * 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/[email protected]
 */
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一樣傳遞到頁面,很容易被不法份子截取到。
但是,只要有適當的預防措施,你就可以用這個簡單的技術實現大量的互動。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved