dongxiezhi9564 2018-04-12 22:28
浏览 104
已采纳

PHP修剪函数不删除空格

I'm doing some tests with learning purpose. I have a PHP script in which I used some functions to see how they work:

  • First I used isset to make sure a var exist

  • Then empty to make sure if a var has some value

  • Finally I used trim to remove whitespaces

After some testing I realized that trim function is not working properly. For example I can still write whitespaceCHARwhitespace, then I used strlen function and I get a 3 as a result. What's wrong with my script?

Btw I would like to know how acceptable is this form validation I would like to avoid some sqlinjection.

Thanks in advance.

<span><?php echo $msg;?></span>
<form method="POST">
    <label for="name" class="white-headers">NAME</label>
    <input type="text" name="name" id="name" class="form-control">
    <label for="last_name" class="white-headers">LAST NAME</label>
    <input type="text" name="last_name" id="last_name" class="form-control">
    <input type="submit" class="btn btn-success" name="submit">
</form>


   $msg="";
  if(isset($_POST["submit"])){
   $name = $_POST["name"];
  $last_name = $_POST["last_name"];
if(!empty(trim($name)) && !empty(trim($last_name))){
    $name_len=strlen($name);
    $last_name_len=strlen($name);
    $msg="<div class='alert alert-success'>
    both fields are set and have some value name =".$name." with ".$name_len." chars and last_name =".$last_name."
    with ".$last_name_len. "chars</div>";
}
else{
    $msg="<div class='alert alert-danger'>
    both fields are set but one or both are empty name =".$name." and last_name =".$last_name."</div>";
}
}
  • 写回答

2条回答 默认 最新

  • drbxr86044 2018-04-12 22:34
    关注

    The only times you're using trim there are when you check whether or not there's anything left after you trim the variables:

    if(!empty(trim($name)) && !empty(trim($last_name))) {
    

    That doesn't affect $name and $last_name.

    trim returns a string with the whitespace removed, but it doesn't change the value of the variable given as an argument. If you want those to be trimmed for later use in your code, you need to set them to their trimmed values, like $name = trim($name), etc.

    In your case, you could probably trim them when you set them from $_POST initially.

    $name = trim($_POST["name"]);
    $last_name = trim($_POST["last_name"]);
    

    Then you can check if there's anything left more simply:

    if ($name && $last_name) {
    

    empty isn't necessary because you know they're set, and zero-length strings evaluate to false.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站