0

I am wondering why: without clicking the submit button on a form on my PHP page, the _POST variable is already set.

For example, I have this piece of code on the web page:

if (isset($_POST)){
     echo "XXXXXXX";
}

It turns out the XXXXXX is echoed just when the page loads the very first time -- at this point I have of course not submitted any data to the server using POST. Why would this be the case?

5 Answers 5

1

As specified on PHP.net, it is automatically created.

This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do global $variable; to access it within functions or methods.

To address your code, it is created, but it's empty.

To better test if the user has made a POST request, simply test for an index on $_POST, like isset($_POST['someFieldName'])

Your code should test if it's empty or not:

if(!empty($_POST)){
    echo "a";
}

or

if(isset($_POST['someFieldName'])){
     echo "a";
}
Sign up to request clarification or add additional context in comments.

Comments

0

$_POST is a superglobal array and it is always set. If you do not pass any value to it using post method it will be empty. So set a value to this array and check whether that value is available or not like this:

if(isset($_POST['submit'])){
 //Do this...
}

Comments

0

The same is true for the $_GET superglobal. These are always set regardless of HTTP Method. You can check if a request was a POST, GET, PUT, etc by checking the REQUEST_METHOD

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // this was an HTTP POST request
}

Comments

0

Check if the variable is empty or not. $_POST will always be set.

So something like the following should work:

if(!empty($_POST['textFieldName'])){
    echo "XXXXXXX";
}

Comments

0

$_POST is superglobal and it's always set as an empty array. Try this, just to understand better:

if(!is_null($_POST))
{
    print_r($_POST);
}

Why is this going to help you to understand? - Because isset checking if a variable is set and is not NULL.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.