终于懂浏览器里面的cookies和session了
在PHP开发中对比起Cookie,session 是存储在服务器端的会话,相对安全,并且不像 Cookie 那样有存储长度限制;
(Php、Asp、Jsp)---:
cookie(客户端)界面没有刷新的话,cookie在本页中是不会起作用的。
session(服务器)session默认是20分钟。
1 <html> 2 <head> 3 <title> 4 5 </title> 6 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> 7 </head> 8 <?php 9 session_start(); 10 11 if(isset($_POST['submit'])){ 12 $user = $_POST['userName']; 13 $pass = $_POST['pass']; 14 15 $conn = mysql_connect("localhost","root","root") or die("链接数据库失败"); 16 mysql_select_db("test"); 17 mysql_query("set names 'utf8'"); 18 19 $sql = "SELECT COUNT( * ) FROM users WHERE `userName` = '$user' AND `pass` = '$pass'"; 20 $result = mysql_query($sql); 21 $row = mysql_fetch_row($result); 22 23 if($row[0]){ 24 $_SESSION["myname"] = $user; 25 26 } 27 } 28 29 if(isset($_SESSION['myname'])){ 30 echo $_SESSION['myname']; 31 } 32 //unset($_SESSION['myname']);//关闭一个session 33 //session_destroy();//关闭多个session 34 ?> 35 36 <body> 37 <form action="login_seesion.php" method="post"> 38 用户名:<input type="text" size="10" name="userName" /><br> 39 密 码:<input type="text" name="pass" /><br/> 40 <input type="submit" name="submit" value="登录"/> 41 </form> 42 </body> 43 44 </html>
1 <html> 2 <head> 3 <title>cookie</title> 4 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> 5 </head> 6 <?php 7 setcookie("mycookie",""); 8 if(isset($_POST['submit'])){ 9 $user = $_POST['userName']; 10 $pass = $_POST['pass']; 11 12 $conn = mysql_connect("localhost","root","root") or die("链接数据库失败"); 13 mysql_select_db("test"); 14 mysql_query("set names 'utf8'"); 15 16 $sql = "SELECT COUNT( * ) FROM users WHERE `userName` = '$user' AND `pass` = '$pass'"; 17 $result = mysql_query($sql); 18 $row = mysql_fetch_row($result); 19 20 if($row[0]){ 21 setcookie("mycookie",$user,time()+1800); 22 } 23 } 24 ?> 25 <body> 26 <?php 27 if(isset($_COOKIE['mycookie'])){ 28 echo "欢迎你:".$_COOKIE['mycookie']; 29 }else{ 30 ?> 31 32 <form action="login.php" method="post"> 33 用户名:<input type="text" size="10" name="userName" /><br> 34 密 码:<input type="text" name="pass" /><br/> 35 <input type="submit" name="submit" value="登录"/> 36 </form> 37 <?php 38 } 39 ?> 40 </body> 41 </html>