PHP实现用户注册并保存数据到文件
首先我们实现功能时,分析实现的步骤是什么,就这个而言,我们应该接收用户提交的数据并进行校验,然后保存在文件,最后给用户反馈。
这里需要注意的是为了避免嵌套过深,这里使用自定义函数来实现,其代码如下:
1 <?php 2 function postback(){ 3 //申明message是全局变量 4 global $message; 5 if (empty($_POST['username'])) { 6 //没有提交用户名或用户名为空 7 $message= "用户名不行"; 8 return; 9 } 10 if (empty($_POST['password'])) { 11 $message= "请输入密码"; 12 return; 13 } 14 if (empty($_POST['confirm'])) { 15 $message= "请输入确认密码"; 16 return; 17 } 18 if ($_POST['password']!==$_POST['confirm']) { 19 echo "两次密码不一致"; 20 return; 21 } 22 if (!(isset($_POST['agree'])&&$_POST['agree']==='true')) { 23 $message= "必须同意注册协议"; 24 return; 25 } 26 //校验完成 27 $message= "注册成功"; 28 $username=$_POST['username']; 29 $password=$_POST['password']; 30 //保存在文件 31 file_put_contents('注册.txt', $username.'|'. $password."\n",FILE_APPEND); 32 } 33 //接受用户提交的数据,保存到文件 34 //1.接受并校验 35 if ($_SERVER['REQUEST_METHOD']==='POST') { 36 postback(); 37 } 38 //2.持久化 39 //3.响应(反馈) 40 ?> 41 <!DOCTYPE html> 42 <html lang="en"> 43 <head> 44 <meta charset="UTF-8"> 45 <title>注册</title> 46 </head> 47 <body> 48 <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> 49 <table border="1"> 50 <tr> 51 <td><label for="username">用户名:</label></td> 52 <td><input type="text" name="username" id="username" value="<?php echo isset($_POST['username']) ? $_POST['username'] : ''; ?>"></td> 53 </tr> 54 <tr> 55 <td><label for="password">密码:</label></td> 56 <td><input type="password" name="password" id="password"></td> 57 </tr> 58 <tr> 59 <td><label for="confirm">确认密码:</label></td> 60 <td><input type="password" name="confirm" id="confirm"></td> 61 </tr> 62 <tr> 63 <td></td> 64 <td><label ><input type="checkbox" name="agree" value="true">同意注册协议</label></td> 65 </tr> 66 <?php if (isset($message)): ?> 67 <tr> 68 <td></td> 69 <td><?php echo $message ?></td> 70 </tr> 71 <?php endif ?> 72 <tr> 73 <td></td> 74 <td><button>注册</button></td> 75 </tr> 76 </table> 77 </form> 78 </body> 79 </html>