<?php
//解决代码else繁琐问题
function postback(){
//php函数里面的变量外面不能访问
//要把外面要访问的变量变成全局变量
//方法一
GLOBAL $message;
//方法二:
//把所有函数里的变量换成$GLOBALS['message']
if (empty($_POST['username'])){
$message= '请输入账号';
return;//满足任何一条不符合的条件函数就不再往下执行
}
if (empty($_POST['password'])){
//把信息用变量存起来
$message= '请输入密码';
return;
}
if(empty($_POST['confirm'])){
$message= '请输入确认密码';
return;
}
if($_POST['confirm']!==$_POST['password']){
$message= '两次输入的密码不一致';
return;
}
if(!(isset($_POST['agree'])&&$_POST['agree']==='on')){
$message='必须同意注册协议';
return;
}
$message='注册成功';
$username=$_POST['username'];
$password=$_POST['password'];
//让以后的账号和密码自动追加,并且以换行隔开,账号和密码通过|隔开
file_put_contents('users.txt', $username .'|'.$password . "\n",FILE_APPEND);
}
if($_SERVER['REQUEST_METHOD']=='POST'){
postback();//函数不执行不影响后面的代码执行
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<table border="1" cellpadding="1" cellspacing="1">
<tr>
<!-- label用的是锚点定位,当点击汉字时,光标自动跳到input里面 -->
<td><input type="text" name="username" id="username" value="<?php echo isset(
<td><label for="username">账号</label></td>$_POST['username'])?$_POST['username']:'' ;?>"></td>
</tr>
<tr>
<td><label for="password">密码</label></td>
<td><input type="text" name="password" id="password"></td>
</tr>
<tr>
<td><label for="confirm">确认账号</label></td>
<td><input type="text" name="confirm" id="confirm"></td>
</tr>
<tr>
<td></td>
<td><label><input type="checkbox" name="agree">同意注册</label></td>
</tr>
<?php if (isset($message)): ?>
<!-- 先判断这个message存不存在,如果存在的话在这个表格中显示错误信息 -->
<tr>
<td></td>
<td><?php echo $message ;?></td>
</tr>
<?php endif ?>
<tr>
<td></td>
<td><button>登录</button></td>
</tr>
</table>
</form>
</body>
</html>