【问题标题】:php htmlspecialchars if statement form inputs trim spaces [duplicate]php htmlspecialchars if语句表单输入修剪空格[重复]
【发布时间】:2014-12-05 04:13:30
【问题描述】:

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

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

我做错了什么?

【问题讨论】:

  • 如果你可以这样检查? trim($_POST["name"] != "") &amp;&amp; ...
  • 想要空格也从中间删除?

标签: php validation trim htmlspecialchars


【解决方案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");
    }
}

【讨论】:

    【解决方案2】:

    只有空格试试

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

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

    根据你的要求安排

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 2015-01-26
      • 2016-11-09
      相关资源
      最近更新 更多