cookie猜數字遊戲(下)------------以及cookie使用的不安全之處
阿新 • • 發佈:2018-11-10
1.通過cookie可以解決上篇中多個使用者對資料的修改,每個COOKIE儲存不同使用者的資料
<?php if(empty($_COOKIE['num'])||empty($_GET['num'])){ //第一次提交,執行這裡面的程式碼 $num=rand(0,100); setcookie('num',$num); }else{ //不是第一次提交 $count = empty($_COOKIE['count']) ? 0:(int)$_COOKIE['count'];//如果是第一次猜count=0,如果不是第一次猜count就為當前的值 if($count<10) { $num1=(int)$_GET['num']; //使用者提交的資料 $num2=(int)$_COOKIE['num'];//儲存在cookie裡面的資料 $result=$num1-$num2; if($result==0){ echo "猜對了"; setcookie('num'); setcookie('count'); }elseif($result>0){ echo "數字太大"; }else{ echo "數字太小"; } setcookie('count',$count+1);//執行完一次就將$count加1 }else{ echo "遊戲結束,挑戰失敗"; setcookie('num'); setcookie('count'); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>猜數字</title> <style> body { padding: 100px 0; background-color: #2b3b49; color: #fff; text-align: center; font-size: 2.5em; } input { padding: 5px 20px; height: 50px; background-color: #3b4b59; border: 1px solid #c0c0c0; box-sizing: border-box; color: #fff; font-size: 20px; } button { padding: 5px 20px; height: 50px; font-size: 16px; } </style> </head> <body> <h1>猜數字遊戲</h1> <p>Hi,我已經準備了一個0~100的數字,你需要在僅有的10機會之內猜對它。</p> <form action="guss.php" method="post"> <input type="number" min="0" max="100" name="num" placeholder="隨便猜"> <button type="submit">試一試</button> </form> </body> </html>
但是在使用COOKIE的時候存在不安全的地方。比如在這個案列中,如果使用者是一個開發人員,通過控制檯,就可以看到COOKIE裡面的值
我們用session來解決這個問題
<?php session_start(); if(empty($_SESSION['num'])||empty($_GET['num'])){ //第一次提交,執行這裡面的程式碼 $num=rand(0,100); $_SESSION['num']=$num; }else{ //不是第一次提交 $count = empty($_SESSION['count']) ? 0:(int)$_SESSION['count'];//如果是第一次猜count=0,如果不是第一次猜count就為當前的值 if($count<10) { $num1=(int)$_GET['num']; //使用者提交的資料 $num2=(int)$_SESSION['num'];//儲存在cookie裡面的資料 $result=$num1-$num2; if($result==0){ echo "猜對了"; unset($_SESSION['num']); unset($_SESSION['count']); }elseif($result>0){ echo "數字太大"; }else{ echo "數字太小"; } $_SESSION['count']=$count+1;//執行完一次就將$count加1 }else{ echo "遊戲結束,挑戰失敗"; unset($_SESSION['num']); unset($_SESSION['count']); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>猜數字</title> <style> body { padding: 100px 0; background-color: #2b3b49; color: #fff; text-align: center; font-size: 2.5em; } input { padding: 5px 20px; height: 50px; background-color: #3b4b59; border: 1px solid #c0c0c0; box-sizing: border-box; color: #fff; font-size: 20px; } button { padding: 5px 20px; height: 50px; font-size: 16px; } </style> </head> <body> <h1>猜數字遊戲</h1> <p>Hi,我已經準備了一個0~100的數字,你需要在僅有的10機會之內猜對它。</p> <form action="session2.php" method="get"> <input type="number" min="0" max="100" name="num" placeholder="隨便猜"> <button type="submit">試一試</button> </form> </body> </html>