Home > Web Front-end > H5 Tutorial > body text

How to use cookies

PHP中文网
Release: 2017-06-20 13:42:33
Original
2683 people have browsed it
  cookie是储存在用户本地终端上的数据。
  在我们登陆网站时有记录密码,也有时间限制比如说7天,5天等等这都是我们利用cookie来写的,
  这就是利用了cookie的会话周期,但cookie同时又是不安全的我们可以打开网页看到用户输入的密码,而且又是依赖于服务器环境的,
  再写cookie时还要设置储存路径,而我们获取出来的值又是字符串,同时它又是非常小的,只有4kb,
  下面我们来封装一下coookie

  封装设置cookie:

  function setCookie(name,value,iDay) {  //传值为名,值,过期时间    if(iDay){ //如果有过期时间的话则执行这个条件

        var oDate=new Date(); //获取当且的事件戳

        oDate.setDate(oDate.getDate()+iDay); //设置过期事件

        document.cookie=name+"="+value+"; path=/; expires="+oDate;//设置cookie

    }else {//如果有过期时间的话则执行这个条件 设置cookie
        document.cookie=name+"="+value+"; path=/"; //名,值以及根目录
    }

}

获取cookie值

function getCookie(name) {

    var arr1=document.cookie.split("; ");  获取cookie值并且用”; “来进行切割成数组

    for(var i=0;i<arr1.length;i++){  //循环本数组

        var arr2=arr1[i].split("="); //再次利用split()方法进行切割为二维数组

        if(arr2[0]==name){  //循环二维数组,当第一个值为你所传的值则返回本数组的第二个值

            return arr2[1];

        }

    }

    return " ";

}

删除cookie 

function removeCookie(name) {

    setCookie("jack","1234",-1);  //再次调用setCookie,关键是把过期时间设置为负值

}

以上就是我对cookie的理解
  
Copy after login

The above is the detailed content of How to use cookies. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!