php htmlspecialchars if语句表单输入修剪空格

时间:2014-12-05 04:13:30

标签: php validation trim htmlspecialchars

如果用户输入空格,我想避免验证表格 但实际上进入空格表格仍然是有效的......

<?php
$name = ""; $email = ""; $comment = ""; $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST"){
    if(!empty($_POST["name"]) && !empty($_POST["email"]) && !empty($_POST["website"]) && !empty($_POST["comment"])){
        $name =    test_input($_POST["name"]);
        $email =   test_input($_POST["email"]);
        $website = test_input($_POST["website"]);
        $comment = test_input($_POST["comment"]);
        echo htmlspecialchars("".$name."".$email."".$website."".$comment."");

    }else{
        echo htmlspecialchars("fill all fields");
    }
}

function test_input($data){
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}
?>

我做错了什么?

2 个答案:

答案 0 :(得分:1)

我认为您应该在修剪后检查数据是否为空您可以尝试以下代码

if ($_SERVER["REQUEST_METHOD"] == "POST"){
        $name =    test_input($_POST["name"]);
        $email =   test_input($_POST["email"]);
        $website = test_input($_POST["website"]);
        $comment = test_input($_POST["comment"]);

    if(!empty($name) && !empty($email) && !empty($website) && !empty($comment)){

        echo htmlspecialchars("".$name."".$email."".$website."".$comment."");

    }else{
        echo htmlspecialchars("fill all fields");
    }
}

答案 1 :(得分:0)

只是空格尝试

$str = '      ';
if (ctype_space($str)) {}

if(trim($str) == '') {} // check a blank string or it's a whitespace

根据您的要求安排

了解更多Check if string is just white space?