찾다
백엔드 개발PHP 튜토리얼怎样使用php与jquery设置和读取cookies_PHP教程

怎样使用php与jquery设置和读取cookies_PHP教程

Jul 21, 2016 pm 02:59 PM
cookieshttpjqueryphp그리고사용규약그리고어떻게상태설정읽다

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
复制代码 代码如下:

// 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
?>




MicroTut: Getting And Setting Cookies With jQuery & PHP | Tutorialzine demo






MicroTut: Getting And Setting Cookies With jQuery & PHP


Go Back To The Tutorial »



 

   

The number above indicates how many times you've visited this page (PHP cookie). Reload to test.




   

 

     

        
            Save
       

   

   

Write some text in the field above and click Save. It will be saved between page reloads with a jQuery cookie.






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                 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一样传递到页面,很容易被不法份子截取到。
但是,只要有适当的预防措施,你就可以用这个简单的技术实现大量的互动。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/328133.htmlTechArticleHTTP协议是一种无状态协议,这意味着你对网站的每一个请求都是独立的,而且因此无法通过它自身保存数据。但这种简单性也是它在互联网...
성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
절대 세션 타임 아웃의 차이점은 무엇입니까?절대 세션 타임 아웃의 차이점은 무엇입니까?May 03, 2025 am 12:21 AM

절대 세션 시간 초과는 세션 생성시 시작되며, 유휴 세션 시간 초과는 사용자가 작동하지 않아 시작합니다. 절대 세션 타임 아웃은 금융 응용 프로그램과 같은 세션 수명주기의 엄격한 제어가 필요한 시나리오에 적합합니다. 유휴 세션 타임 아웃은 사용자가 소셜 미디어와 같이 오랫동안 세션을 활성화하려는 응용 프로그램에 적합합니다.

세션이 서버에서 작동하지 않으면 어떤 조치를 취 하시겠습니까?세션이 서버에서 작동하지 않으면 어떤 조치를 취 하시겠습니까?May 03, 2025 am 12:19 AM

서버 세션 고장은 다음 단계를 따라 해결할 수 있습니다. 1. 서버 구성을 확인하여 세션이 올바르게 설정되었는지 확인하십시오. 2. 클라이언트 쿠키를 확인하고 브라우저가 지원하는지 확인하고 올바르게 보내십시오. 3. Redis와 같은 세션 스토리지 서비스가 정상적으로 작동하는지 확인하십시오. 4. 올바른 세션 로직을 보장하기 위해 응용 프로그램 코드를 검토하십시오. 이러한 단계를 통해 대화 문제를 효과적으로 진단하고 수리 할 수 ​​있으며 사용자 경험을 향상시킬 수 있습니다.

session_start () 함수의 중요성은 무엇입니까?session_start () 함수의 중요성은 무엇입니까?May 03, 2025 am 12:18 AM

session_start () iscrucialinphpformanagingUsersessions.1) itiniteSanewsessionifnoneexists, 2) ResumesAnxistessions, and3) setSasessionCookieForContInuityAcrosrequests, enablingplicationsirecationSerauthenticationAndpersonalizestContent.

세션 쿠키를 위해 httponly 플래그를 설정하는 것이 중요합니까?세션 쿠키를 위해 httponly 플래그를 설정하는 것이 중요합니까?May 03, 2025 am 12:10 AM

XSS 공격을 효과적으로 방지하고 사용자 세션 정보를 보호 할 수 있기 때문에 httponly 플래그를 설정하는 것은 세션 쿠키에 중요합니다. 구체적으로, 1) httponly 플래그는 JavaScript가 쿠키에 액세스하는 것을 방지합니다. 2) PHP 및 Flask에서 SetCookies 및 Make_response를 통해 깃발을 설정할 수 있습니다. 3) 모든 공격으로부터 방지 할 수는 없지만 전체 보안 정책의 일부가되어야합니다.

웹 개발에서 PHP 세션은 어떤 문제를 해결합니까?웹 개발에서 PHP 세션은 어떤 문제를 해결합니까?May 03, 2025 am 12:02 AM

phpssessionssolvetheproblemofmainingstateacrossmultiplehtttprequestsbystoringdataontheserversociatingititwithauniquessessionid.1) theStoredAserver-side, 일반적으로, 일반적으로 and insessionsecietoretoretrievedata.2) sessionsenhances

PHP 세션에 어떤 데이터를 저장할 수 있습니까?PHP 세션에 어떤 데이터를 저장할 수 있습니까?May 02, 2025 am 12:17 AM

phpsessionscanstorestrings, 숫자, 배열 및 객체 1.Strings : TextDatalikeUsernames.2.numbers : integorfloatsforcounters.3.arrays : listslikeshoppingcarts.4.objects : complexStructuresThatareserialized.

PHP 세션을 어떻게 시작합니까?PHP 세션을 어떻게 시작합니까?May 02, 2025 am 12:16 AM

tostartAphPessession, us

세션 재생이란 무엇이며 보안을 어떻게 개선합니까?세션 재생이란 무엇이며 보안을 어떻게 개선합니까?May 02, 2025 am 12:15 AM

세션 재생은 세션 고정 공격의 경우 사용자가 민감한 작업을 수행 할 때 새 세션 ID를 생성하고 이전 ID를 무효화하는 것을 말합니다. 구현 단계에는 다음이 포함됩니다. 1. 민감한 작업 감지, 2. 새 세션 ID 생성, 3. 오래된 세션 ID 파괴, 4. 사용자 측 세션 정보 업데이트.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구