PHP HTMLspecialchars if 语句表单输入修剪空格


php htmlspecialchars if statement form inputs trim spaces

我想避免在用户输入空格时验证表单,
但实际上输入空格表单仍然有效...

<?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;
}
?>

我做错了什么?

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

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");
    }
}

对于只是空格尝试

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

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

根据您的要求安排

查看更多 检查字符串是否只是空格?