写一个php的猜数字的小程序,提高自己对php的熟悉程度。
1 <?php 2 $count=rand(0,100); 3 $number = (isset($_POST['number'])) ? $_POST['number']:$count; 4 5 if(!isset($_POST['guess'])){ 6 $message = "please enter a number"; 7 } 8 elseif(!is_numeric($_POST['guess'])){ 9 $message = "please make sure you entered a number"; 10 } 11 elseif($_POST['guess'] > $number){ 12 $message = "too big"; 13 } 14 elseif($_POST['guess'] < $number){ 15 $message = "too small"; 16 } 17 else if($_POST['guess'] == $number){ 18 header("Location:success.php"); 19 } 20 else{ 21 $message = "so confused"; 22 } 23 ?> 24 25 <!doctype html> 26 <html> 27 <head> 28 <title>A number guess game</title> 29 <meta charset="UTF-8"> 30 <title>Document</title> 31 </head> 32 <body> 33 <h1><?php echo $number?></h1> 34 <h1><?php echo $message?></h1> 35 <form action = "<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> 36 <p><label for="guess">Type your answer</label> </p> 37 <input type="text" id="guess" name="guess"/> 38 <input type="hidden" name="number" value = "<?php echo $number?>" > 39 <button type="submit" name="submit" value="submit">Submit</button> 40 </form> 41 </body> 42 </html>
总结:
1.第2行代码:$number = (isset($_POST['number'])) ? $_POST['number']:$count; 这样写可以保证每次刷新页面时答案不会变化;
2.第18行代码:header("Location:success.php");转去success.php页面;
3.第35行代码: action = "<?php echo $_SERVER['PHP_SELF']; ?>";传回本页面;
4.第38行代码:<input type="hidden" name="number" value = "<?php echo $number?>" > 不在页面显示而传值;
5.(不在本项目中):<?php phpinfo(); ?>输出PHP的安装信息