PHP实现用户注册并保存数据到文件

首先我们实现功能时,分析实现的步骤是什么,就这个而言,我们应该接收用户提交的数据并进行校验,然后保存在文件,最后给用户反馈。

这里需要注意的是为了避免嵌套过深,这里使用自定义函数来实现,其代码如下:

<?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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值