这是我的php验证码!
<?php //------------------------------------------------------------------------------>PHP VALIDATION
$user="";
$pass="";
$nameErr="";
$passErr="";
//$pattern='/^[a-zA-Z0-9@_ ]*$/';
if($_SERVER['REQUEST_METHOD']=='POST')
{
if(empty($_POST['uname']))
{
$nameErr='Enter Your Name!';
}
else
{
$user = test_input($_POST['uname']);
if(!preg_match('/^[a-zA-Z0-9@_]*$/',$user))
{
$nameErr=' Re-Enter Your Name! Format Inccorrect!( only alpha, numbers,@_ are allowed)';
}
}
if(empty($_POST['pas']))
{
$passErr='Enter Your Password!';
}
else
{
$user = test_input($_POST['pas']);
if(!preg_match('/^[a-zA-Z0-9@_]*$/',$pass))
{
$passErr='Invalid Format! Re-Enter Password!';
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
HTML:
<html>
<body>
<div id='shw'><?php echo $user;?></div>
<fieldset id='fld'>
<form method='post' name='f1' action='<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>'>
<table>
<tr>
<td>
User Name:<input type='text' id='uname' name='uname' class='uname' placeholder='USERNAME' autocomplete='off' autofocus maxlength='25'><span class='error'>*</span>
Password:<input type='password' id='pass' class='pass' name='pas' placeholder='PASSWORD' autocomplete='off'>
<input type='submit' name='submit' id='loggin' value='LOGIN' class='login' onclick='val()'>
</td>
</tr>
</table>
</form>
</fieldset>
<div class='errormsg' id='errmsg'><?php echo $nameErr;?></div>
</div>
</body>
</html>
我有验证问题我希望在提交后显示用户名。 问题是我的用户名if else运行正常,但它会跳过密码部分。我认为它也会验证传递字段然后只显示用户名! 请帮忙!
答案 0 :(得分:1)
$user = test_input($_POST['pas']);
应为$pass = test_input($_POST['pas']);
你当前的代码在第一个if..else
块中设置$ user,并不是PHP跳过你的第二个if...else
块,只是无论这个块会做什么,ûser已经设置好了。
如果您不希望在密码无效时显示$ user,请稍后在代码中设置$ user:
$ nameErr = null;
$ passErr = null;
if (empty($_POST['uname'])) {
$nameErr = 'Enter Your Name!';
} else {
$userTest = test_input($_POST['uname']);
if (!preg_match('/^[a-zA-Z0-9@_]*$/', $userTest)) {
$nameErr = ' Re-Enter Your Name! Format Inccorrect! (only alpha, numbers, @_ are allowed)';
} else {
$valid++;
}
}
if (empty($_POST['pas'])) {
$passErr = 'Enter Your Password!';
} else {
$pass = test_input($_POST['pas']);
if (!preg_match('/^[a-zA-Z0-9@_]*$/', $pass)) {
$passErr = 'Invalid Format! Re-Enter Password!';
} else {
$valid++;
}
}
if (is_null($nameErr) && is_null($passErr)) {
$user = $_POST['uname']
}
在这里,我只是检查$ nameErr和$ passErr在测试结束时是否仍为空。如果两者都为null,则可以设置$ user,因为未检测到错误。