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条)

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错