PHP - 总是在表单中获得错误

时间:2017-10-13 00:08:28

标签: php forms

我有这个表单,但我一直收到"You cannot use less than 7 characters in your shout."错误。这就是我所拥有的,对我来说似乎很好:

        if(isset($_POST['submit'])) {
            $shout = strip_tags($_POST['shout']);
            $value = (!empty($shout)) ? 'value="' . $shout . '"' : '';

            if(empty($shout)) {
                $response[] = '<div class="alert alert-danger"><strong>Error!</strong> Your shout cannot be empty.</div>';
            } elseif($shout > 50) {
                $response[] = '<div class="alert alert-danger"><strong>Error!</strong> You cannot use more than 50 characters in your shout.</div>';
            } elseif($shout < 7) {
                $response[] = '<div class="alert alert-danger"><strong>Error!</strong> You cannot use less than 7 characters in your shout.</div>';
            } else {
                $response[] = '<div class="alert alert-success"><strong>Success!</strong> Your shout has been posted and placed in the shoutbar.</div>';
            }
        }

        if(isset($response)) {
            foreach($response as $respons) {
                echo $respons;
            }
        }
    ?>
<form method="post">
    <table class="table">
        <tr>
            <td><strong>Your shout</strong></td>
            <td><input type="text" name="shout" placeholder="Type your shout" <?php echo $value; ?> class="form-control"></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Post it" name="submit" class="btn btn-default"></td>
        </tr>
    </table>
</form>

为什么我一直收到此错误?我键入的输入介于7到50个字符之间,因此它应该采用else路径。

2 个答案:

答案 0 :(得分:2)

您需要strlen($shout)进行比较。您将$shout作为字符串进行比较,并将整数7转换为字符串进行比较,但您打算将整数长度与另一个整数值进行比较

答案 1 :(得分:1)

你需要比较长度,使用mb_strlen()(多字节)而不是strlen(),自PHP 4&gt; = 4.0.6以来可用,以避免以非标准字符结尾的字符串长度发生致命错误,如latin tilde( á,é,í,ó,ú,ñ)或任何其他特殊字符。

http://php.net/manual/es/function.mb-strlen.php