一、方案一:使用post方法(基本版)
<?php
if($_SERVER['REQUEST_METHOD']==='GET'){
//登录网站时,采用的是get的方法
$num=rand(0,100);
//不能存在文件中,因为有可能有多个用户使用
//cookie是每个用户自己本地客户端保存的,每个用户存的都是自己要猜的数字
setcookie('num',$num);
}else{
//用户点击了试一试,采用的是POST的方法
//$_POST['num']是用户试一试的数字,$_COOKIE['num']是用户要猜的数字
$result=(int)$_POST['num']-(int)$_COOKIE['num'];
if($result==0){
echo '猜对了';
}elseif($result>0){
echo '太大了';
}else{
echo '太小了';
}
}
?>
<!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>
<!-- post方法 -->
<form action="test.php" method="POST">
<input type="number" min="0" max="100" name="num" placeholder="随便猜">
<button type="submit">试一试</button>
</form>
</body>
</html>
![](https://images2018.cnblogs.com/blog/1319779/201806/1319779-20180623120535301-300522293.gif)
二、方案二:使用get方法(完善版)
- 基本概念的实现
- 解决10次限制的问题
- session解决F12可以查看密码的“漏洞”
<?php
//开启session
session_start();
if(empty($_COOKIE['num'])){
//登录网站时,产生随机数
$num=rand(0,100);
//setcookie('num',$num);
$_SESSION['num']=$num;
}else{
//设置次数限制
$count=empty($_SESSION['count'])? 0 : (int)$_SESSION['count'];
if($_COOKIE['count']<10){
$result=(int)$_GET['num']-(int)$_SESSION['num'];
if($result==0){
$message= '猜对了';
//游戏结束,出现开始,删除cookie(一个参数)
unset($_SESSION['num']);
unset($_SESSION['count']);
}elseif($result>0){
$message= '太大了';
}else{
$message= '太小了';
}
$_SESSION['count']=$count+1;
}else{
//游戏结束
$message= '游戏结束';
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>
<?php if(isset($message)): ?>
<p><?php echo $message; ?></p>
<?php endif ?>
<!-- GET方法 -->
<form action="test.php" method="GET">
<input type="number" min="0" max="100" name="num" placeholder="随便猜">
<button type="submit">试一试</button>
</form>
</body>
</html>
![](https://images2018.cnblogs.com/blog/1319779/201806/1319779-20180623121647492-1199560648.gif)