一、分析:php
====不推荐这种======== <?php function foo(){ // global $message; if(empty($_POST['username'])){ echo "要先输入名字"; return; }else{ if(empty($_POST['password'])){ echo "请输入密码"; return; }else{ if(empty($_POST['confirm'])){ echo "请确认密码"; return; }else{ if ($_POST['password'] !== $_POST['confirm']) { $GLOBALS['message'] = '两次输入的密码不一致'; return; }else{ if(!(isset($_POST['agree'])&&isset($_POST['agree'])=='on')){ echo "赞成协议了吗"; return; }else{ $username=$_POST['username']; $password=$_POST['password']; file_put_contents('users.txt', $username.'|'.$password."\n",FILE_APPEND); } if ($_SERVER['REQUEST_METHOD'] === 'POST') { foo(); } ?> ============================================================================= <?php function foo(){ //咱们的目的是每次提交表单的时候,都要看看里面的内容是否为空,若是第一个为空,里面的文本框就不能输入,用(return)能够让程序中止,可是return 只能用在函数中,因此咱们构建了一个函数 // global $message; //这里必定要设置为全局变量,不然下面html代码中的$message不能使用 if(empty($_POST['username'])){ echo "要先输入名字"; return; } if(empty($_POST['password'])){ echo "请输入密码"; return; } if(empty($_POST['confirm'])){ echo "请确认密码"; return; } if ($_POST['password'] !== $_POST['confirm']) { $GLOBALS['message'] = '两次输入的密码不一致'; return; } if(!(isset($_POST['agree'])&&isset($_POST['agree'])=='on')){ echo "赞成协议了吗"; return; } $username=$_POST['username']; $password=$_POST['password']; file_put_contents('users.txt', $username.'|'.$password."\n",FILE_APPEND); } if ($_SERVER['REQUEST_METHOD'] === 'POST') { foo(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <table> <tr> <td><label for="username">用户名</label></td> <td><input type="text" name="username"></td> </tr> <tr> <td><label for="password">密码</label></td> <td><input type="password" name="password"></td> </tr> <tr> <td><label for="confirm">确认密码</label></td> <td><input type="password" name="confirm" id="confirm"></td> </tr> <tr> <td></td> <td><label><input type="checkbox" name="agree" value="on"> 赞成注册协议</label></td> </tr> <?php if (isset($message)): ?> <tr> <td></td> <td><?php echo $message; ?></td> </tr> <?php endif ?> <tr> <td><label for="button"></label></td> <td><input type="submit" name="button"></td> </tr> </table> </form> </body> </html>