开发者

php - check an empty string with === '' does not work

When I test to see if the textarea in my form is empty to do a redirect so it doesn't submit it in php, it doesn't work.

The textarea is named $_POST['message'], I know the variable exists because if I do this statement;

if (isset($_POST['message'])) {
    header('Location:/');
    exit();
}

Then it a开发者_如何转开发lways redirects back to the index page so the variable must exist, although if I do this;

if (empty($_POST['message'])) {
    header('Location:/');
    exit();
}

It does not work, also tried with all three combos of =/==/===

if ($_POST['message'] === '') {
    header('Location:/');
    exit();
}

And also...

if (empty(trim($_POST['message']))) {
    header('Location:/');
    exit();
}

Any ideas why this is happening? And how I can prevent it, I really need to stop it as I do not want empty values in my mysql table.

I did some research and it seems some other people have had this problem, but I have seen no answer as of yet.


You probably have some whitespaces in the string, which isn't stripped by trim().

Do a strlen() on it to see what's up, and then log it byte by byte (http://stackoverflow.com/questions/591446/how-do-i-get-the-byte-values-of-a-string-in-php).

One thing you could think about is to make sure your textarea doesn't have any content in the markup (spaces, linkebreaks, whatever), like this:

<textarea></textarea>


I'm pretty sure your last try would work if you'd do it correctly, this:

if (empty(trim($_POST['message']))) {
    // ...
}

...is a syntax error. empty is a language construct and does not accept expressions. Try:

$message = isset($_POST['message']) ? trim($_POST['message']) : '';
if (empty($message)) {
    // $_POST['message'] is empty
}


This will ignore all input lengths below 3 chars:

if (isset($_POST['message']) && strlen(trim($_POST['message'])) < 3) {
    header('Location:/');
    exit();
}

However, if you just want to check, if a form was submitted, ask for the submit-button:

<input type="submit" name="submit" value="send" />

the php code would be

if (!array_key_exists('submit', $_POST)) {
    header('Location:/');
    exit();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜