>我正在尝试使用 $_POST 方法从 HTML 表单中获取用户名和密码,但是我在给定输入时遇到未定义的索引错误。
我的索引文件的表单部分如下
<form class="form-signin" role="form"action="" method="post">
<h2 class="form-signin-heading">title<em class='current'>title</em></h2>
<input id="username" type="username" class="form-control" placeholder="Username" required autofocus>
<input id="password" type="password" class="form-control" placeholder="Password" required>
<input name ="submit" type="submit" value="sign in">
</form>
我的 PHP 脚本(称为 auth.php)也包含在索引文件的顶部。
这是我的身份验证.php脚本代码示例
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
echo "auth is called";
if(isset($_POST['submit'])){
echo "submit is pressed";
//this if statement enters when submit is pressed
if(empty($_POST['username']) || empty($_POST['password'])) {
echo "Username or Password is empty";
//this if statement enters too, even with input given
}
else{
echo "YAY";
}
}
?>
"用户名或密码为空"语句不断被打印,即使我在输入字段中输入用户名和密码也是如此。问题出在哪里
缺少"name"attribute in input
字段,它应该是
编辑2:用户名input
中缺少type="text"
<input type="text" name='username' id="username" class="form-control" placeholder="Username" required autofocus>
<input name='password' id="password" type="password" class="form-control" placeholder="Password" required>
更正您的表单 , 1.姓名缺失,2。没有用户名名称的数据类型
<form class="form-signin" role="form" action="" name="loginform" method="post">
<h2 class="form-signin-heading">title<em class='current'>title</em></h2>
<input id="username" name="username" type="text" class="form-control" placeholder="Username" required autofocus>
<input id="password" name="password" type="password" class="form-control" placeholder="Password" required>
<input name="submit" type="submit" value="sign in">
</form>
<input id="username" name="username" type="username" class="form-control" placeholder="Username" required autofocus>
<input id="password" type="password" name="password" class="form-control" placeholder="Password" required>
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
echo "auth is called";
if(isset($_POST['submit'])){
echo "submit is pressed";
//this if statement enters when submit is pressed
if(empty($_POST['username']) || empty($_POST['password'])) {
echo "Username or Password is empty";
//this if statement enters too, even with input given
}
else if(empty($_POST['username']){
echo "Username is empty";
}
else if(empty($_POST['password']){
echo "Password is empty";
}
else{
echo "YAY";
}
}
?>
输入type = text
和name attr
必需
<input name='username' id="username" type="text" class="form-control" placeholder="Username" required autofocus>
如果未获得所需的输出,请使用 print_r()
或 var_dump
检查值。
这将帮助您检查代码的哪一部分出现故障。如果你这样做了,你会发现你的html表单内容只有问题,因为你不会打印任何字段内容,你可以很容易地把它整理出来......
将username
输入的类型设置为 "text"
:
<input name='username' id="username" type="text" class="form-control" placeholder="Username" required autofocus>
<input name='password' id="password" type="password" class="form-control" placeholder="Password" required>