!empty(trim($_POST['username']

匆匆过客 提交于 2019-12-05 20:35:56

问题


Ok the problem is that when i use the trim function doesnt work but when i run the code without the trim function its working, but not properly working(the form accepts whitespaces)

<?php
session_start();
unset($_SESSION['username']);

 if (isset($_SESSION['username']))
    {echo "You are in already";}

 else if ($_SERVER['REQUEST_METHOD'] == 'POST')
 {      

 if (!empty(trim($_POST['username'])) && !empty(trim($_POST['email'])))
    {
        $uname = htmlentities($_POST['username']);
        $email = htmlentities($_POST['email']);
  $_SESSION['username'] = $uname;

            echo "THANKS: " . $uname . "<br />";
    }
 else { echo "fill the goddemn field"; }


  } else { ?>

<form action="index.php" method="post">
 <label for="username">USERNAME:</label>
 <input type="text" name="username" />
 <label for="E-MAIL">E-mail:</label>
 <input type="text" name="email" />
 <input type="submit" value="Enter" />
</form>


<?php    } ?>

I tried the manual http://php.net/manual/en/function.trim.php but it was hard to read and I didn't figure out anything.


回答1:


As the PHP manual says:

empty — Determine whether a variable is empty

In your case, trim is a function call, not a variable.

If you really want to do your if statement inline, you can use something like:

if (!empty($var=trim($_POST['username'])) && !empty($var=trim($_POST['email'])))

But a better implementation should be:

$username = array_key_exists('username', $_POST) ? trim($_POST['username']) : null;
$email = array_key_exists('email', $_POST) ? trim($_POST['email']) : null;

if (!empty($username) && !empty($email))
{
    (...)


来源:https://stackoverflow.com/questions/16988388/emptytrim-postusername

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!