1

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 always 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.

JMax
  • 26,109
  • 12
  • 69
  • 88
carlgcoder
  • 229
  • 1
  • 3
  • 10

3 Answers3

2

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>
jishi
  • 24,126
  • 6
  • 49
  • 75
2

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
}
netcoder
  • 66,435
  • 19
  • 125
  • 142
0

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();
}
Lars
  • 5,757
  • 4
  • 25
  • 55