在处理程序时,我遇到了一个未知错误。结果是,我的代码绕过了两个if
语句。这是我的代码:
<?
session_start();
if ($_POST){
$ao = trim($_POST['amountof']);
$continue = true;
if (strlen($ao) < 1){ ####First If-Statement Bypassed####
$continue = false;
$_SESSION['error'] = "Please enter in a value!";
}
if (strlen($ao) > 20){ ####Second If-Statement Bypassed####
$continue = false;
$_SESSION['error'] = "Your value has exceeded 20!";
}
if (!is_numeric($ao)){
$continue = false;
$_SESSION['error'] = "Value is not numeric!";
}
}
?>
<form method="post">
<?
if (isset($_SESSION['error'])){
print "<span style='"color: red; font-weight: bold;'">" . $_SESSION['error'] . " </span><br />";
}
?>
How many letters are you planning to process?<br />
<span style="font-size:.8em; color: grey;">You may not exceed 20</span><br />
<input type="text" name="amountof" style="width:25px;" maxlength="2"/>
<input type="submit" value="Continue" />
</form>
<? unset($_SESSION['error']); ?>
代码中标记了被绕过的if语句。非常感谢。
试试看:
<?php
session_start();
$_SESSION['error']='';
if (isset($_POST['amountof'])){
$ao = trim($_POST['amountof']);
$continue = true;
if (strlen($ao) < 1){
$continue = false;
$_SESSION['error'].= "Please enter in a value!<br/>";
}
if (!is_numeric($ao)){
$continue = false;
$_SESSION['error'].= "Value is not numeric!<br/>";
}
elseif ($ao > 20){
$continue = false;
$_SESSION['error'].= "Your value has exceeded 20!";
}
}
?>
<form method="post">
<?php
if (!empty($_SESSION['error'])){
//......
或简化(注意,用户可以键入负值或0当前将通过测试)
if (!is_numeric($ao) || $ao<1 || $ao>20){
$continue = false;
$_SESSION['error']= "Please enter in a numeric value between 1 and 20";
}
在没有看到一些示例数据的情况下,我认为您只是覆盖了错误变量,而不是绕过if语句。让我们在不输入任何内容的情况下运行代码。
第一个if语句中的代码运行,因为strlen($ao)将小于1$_SESSION['error']将是"请输入一个值!"
现在,第二个if语句中的代码没有运行,因为strlen($ao)显然没有超过20。
运行第三个if语句中的代码,因为空字符串不是数字。由于您正在覆盖$_SESSION['error'],因此变量将只是"值不是数字!"。因此,如果绕过语句,它将出现在第一个if语句中。
尝试连接错误字符串,而不是覆盖。
编辑:使用Molle博士在我回答之前发布的代码片段。
您需要使用
if(isset($_POST)) {
在第二行,而不是您正在使用的,因为$_POST
的行为类似于一个数组。