問題: 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">密 碼</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分開寫,寫在不同的文件中
如果你有其他更換好的方法,歡迎分享