Reputation: 175
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?
Upvotes: 0
Views: 538
Reputation: 51
$_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.
Upvotes: 0
Reputation: 3322
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";
}
Upvotes: 0
Reputation: 6836
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";
}
Upvotes: 1
Reputation: 6893
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
}
Upvotes: 0
Reputation: 1527
$_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...
}
Upvotes: 0