Home > Backend Development > PHP Tutorial > php 之 cookie 跟 session 简单解读(笔记)

php 之 cookie 跟 session 简单解读(笔记)

WBOY
Release: 2016-06-13 10:31:19
Original
777 people have browsed it

php 之 cookie 和 session 简单解读(笔记)

cookie:保存值在本地,也就是客户端。优点是可以设置保存多长长时间,但不安全

session : 保存在服务器,关掉浏览器就木了

如:登陆页面有个文本框的名字为 "username",登陆成功后在显示页(xs.php)面显示?登陆的用户名 ,并有个退出的文字按钮

登陆页面代码如下:

$username=$_POST['username'];   //得到文本框中的值,这里就是用户名setcookie('username',$username,time()+3600);// 这里设置 cookie的名称,指向设置的值(就是指向上面用户名),然后是保存时间为3600
Copy after login

显示页面代码:?

echo "用户名为:".$_COOKIE[username];    //取得用户名  echo "<a href="xs.php?out=out" mce_href="xs.php?out=out">退出</a>";  //给一退出用户名的按钮链接,原理就是重新设置cookie的值为空  if($_GET['out'])  {    setcookie('username','');      //这里就设置了为空    echo "<mce:script type="text/javascript"><!--location.href='login.php'// --></mce:script>"; //重新跳转到登陆页面  }  
Copy after login

?? ?上面最后 echo 是这样的:echo "<script>location.href='login.php'</script>";

session?

?登陆页面代码

session_start();   //启动session,这里必须写文件的最上面$username=$_POST['username'];$_SESSION[username]=$username;
Copy after login

?显示页面:

session_start();echo "欢迎您".$_SESSION[username];echo "<a href="xs.php?out=out" mce_href="xs.php?out=out">退出</a>";if($_GET['out'])  {  	unset($_SESSION[username]);  //这里就是清除session	echo "<mce:script type="text/javascript"><!--location.href='login.php'// --></mce:script>";  }
Copy after login
?

?

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