-1

I'm trying to only display some content if values were posted to my page. I'm doing this using the following code:

if(isset($_POST)){
    echo "it is in here";
}

The value in the echo is appearing even when the page loads, why would that be?

4
  • 1
    Regardless of whether information was posted or not $_POST will always exist because it is a pre-set system array, you could try doing if (count($_POST) > 0)
    – Prime
    Apr 23, 2015 at 1:08
  • 1
    Or check for the existence of a submit button in your form - it's a fairly standard way to do it... if (isset($_POST['submitButton'])) { // ... }
    – scrowler
    Apr 23, 2015 at 1:10
  • $_POST is always accessible to the receiving script since its automatically generated by PHP. If you want to check if your request was initiated by a submitted form its usually best to simply check for existence of a form's submit button. Something like if (isset($_POST['submit_form'])) { ... }.
    – user188654
    Apr 23, 2015 at 1:10
  • If I recall correctly this will display either a value is set or not, it would be better if you test the field you submit like this: 'if(isset($_POST['field_name']))'
    – H Aßdøµ
    Apr 23, 2015 at 1:11

3 Answers 3

2

$_POST are always set, try empty function instead. Try this:

    if(!empty($_POST)){
        echo "it is in here";
    }
2
  • 2
    Not ideal - anyone could post foo=bar to your web page and have that content show up
    – scrowler
    Apr 23, 2015 at 1:11
  • yup, need to do some checking before content shows. for example, set a hidden input with secret name and value.
    – Eng Cy
    Apr 23, 2015 at 1:14
1

$_POST is one of the superglobals in PHP Superglobals - PHP Manual

isset() will return TRUE on any of them, since they are

built-in variables that are always available in all scopes

according to the official manual.

You should either check

isset($_POST['a specific post parameter name'])

Or, check:

$_SERVER['REQUEST_METHOD'] === 'POST'

to determine.

0

$_POST isset even if it's empty

You can use !empty (not empty), i.e.:

if(!empty($_POST)){
    echo "it is in here";
}

Although, you should normally check if a specific $_POST parameter isset, i.e.:

if(isset($_POST["something"])){
    echo "something is in here";
}

Resources:

function.empty

reserved.variables.post

function.isset

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.