php将用户信息提交到表单并且以txt文档打印出来

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36759976/article/details/83450519

1、分析:

====不推荐这种========

<?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>

猜你喜欢

转载自blog.csdn.net/qq_36759976/article/details/83450519