解决php和html混写,form表单未提交,php就执行的问题

问题: php和html混写,文件存储为php文件,无论php是写在html之前,还是之后,此时在浏览器中打开,展现的是php先执行的结果,如图


代码如下

<?php
    $username = '';
    $userpwd = '';
    session_start();
    if(isset($_POST['username'])){
        $username = $_POST['username'];
    }
    if(isset($_POST['userpwd'])){
        $userpwd = $_POST['userpwd'];
    }
    //简单校验用户名和密码不为空
       if(empty($username)){
          eixt('<script>alert("错误:用户名不能为空")</script>');
      }
      if(empty($userpwd)){
          eixt('<script>alert("错误:密码不能为空")</script>');
      }
    
?>
<!DOCTYPE html>
<html>
<head>
    <title>newLife</title>
</head>
<body>
    <div class="login">
        <h1>欢迎来到newLife</h1>
        <div>
            <form method="post" action="login.php">
                <ul>
                    <li>
                        <label for="loginName">用户名</label>
                        <input type="text" name="username" id="loginName" placeholder="请输入登录名" />
                    </li>
                    <li>
                        <label for="loginPwd">密&nbsp;&nbsp;&nbsp;码</label>
                        <input type="password" name="userpwd" id="loginPwd" placeholder="请输入密码"/>
                    </li>
                    <li>
                        <input type="submit"  name="submit"value="登录"  />
                    </li>
                </ul>
            </form>
        </div>
    </div>
</body>
</html>

问题原因

首先文件为php文件,在php文件中php代码的优先级高于html,因此会先执行php代码

解决方案

1.在php文件中最开始的位置用if做一个判断,判断表单提交了,再执行php代码

if(isset($_POST['submit'])){
 提交后需要执行的代码
}

2.php和html分开写,写在不同的文件中

如果你有其他更换好的方法,欢迎分享

posted @ 2018-11-06 12:38  MrBear  阅读(2365)  评论(0编辑  收藏  举报