首先我们实现功能时,分析实现的步骤是什么,就这个而言,我们应该接收用户提交的数据并进行校验,然后保存在文件,最后给用户反馈。
这里需要注意的是为了避免嵌套过深,这里使用自定义函数来实现,其代码如下:
<?php
function postback(){
//申明message是全局变量
global $message;
if (empty($_POST['username'])) {
//没有提交用户名或用户名为空
$message= "用户名不行";
return;
}
if (empty($_POST['password'])) {
$message= "请输入密码";
return;
}
if (empty($_POST['confirm'])) {
$message= "请输入确认密码";
return;
}
if ($_POST['password']!==$_POST['confirm']) {
echo "两次密码不一致";
return;
}
if (!(isset($_POST['agree'])&&$_POST['agree']==='true')) {
$message= "必须同意注册协议";
return;
}
//校验完成
$message= "注册成功";
$username=$_POST['username'];
$password=$_POST['password'];
//保存在文件
file_put_contents('注册.txt', $username.'|'. $password."\n",FILE_APPEND);
}
//接受用户提交的数据,保存到文件
//1.接受并校验
if ($_SERVER['REQUEST_METHOD']==='POST') {
postback();
}
//2.持久化
//3.响应(反馈)
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="1">
<tr>
<td><label for="username">用户名:</label></td>
<td><input type="text" name="username" id="username" value="<?php echo isset($_POST['username']) ? $_POST['username'] : ''; ?>"></td>
</tr>
<tr>
<td><label for="password">密码:</label></td>
<td><input type="password" name="password" id="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="true">同意注册协议</label></td>
</tr>
<?php if (isset($message)): ?>
<tr>
<td></td>
<td><?php echo $message ?></td>
</tr>
<?php endif ?>
<tr>
<td></td>
<td><button>注册</button></td>
</tr>
</table>
</form>
</body>
</html>