問題描述
為什麼我的 php 代碼繞過了一些 if 語句? (Why is my php code bypassing a few if statements?)
As I was working with my program, I had come up with an unknown error. What happens is that my code is bypassing two if
statements. Here's my code:
<?
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']); ?>
The if statements that are bypassed are marked in the code. Thank you!
參考解法
方法 1:
Try that:
<?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'])){
//......
or simplified(note that the user may type negative values or 0 what currently will pass the test)
if (!is_numeric($ao) || $ao<1 || $ao>20){
$continue = false;
$_SESSION['error']= "Please enter in a numeric value between 1 and 20";
}
方法 2:
Without seeing some sample data, I believe you are simply overwriting the error variable, not bypassing the if statements. Let's run through the code with the case where nothing is entered.
The code inside the first if statement runs, since the strlen($ao) would be less than one. $_SESSION['error'] would be "Please enter in a value!"
Now the code in the second if statement doesn't run, since strlen($ao) is obviously not over 20.
The code in the third if statement runs, since an empty string is not numeric. Since you are overwriting $_SESSION['error'], the variable would simply be "Value is not numeric!". Thus it would appear the first if statement is bypassed.
Try concatenating the error string instead of overwriting.
EDIT: By using the code snippet posted by Dr Molle just before I answered.
方法 3:
You need to use
if(isset($_POST)) {
on line two, instead of what you're using, because $_POST
behaves like an array.
(by slippery、Dr.Molle、Josh S、David)