问题
I want to check if $_POST['submit'] is posted.
My original code was:
if ($_POST['submit']) { }
But I have a PHP notice with this code - "Undefined index: submit in..."
So to remove the notice I have to write this:
if (isset($_POST['submit'])) { }
But this is pointless because $_POST array is global and it return always true. Also if I want to check if $_POST['submit'] is not 0 without PHP notice I have to write this:
if (isset($_POST['submit']) && $_POST['submit'] != 0) { }
In this particular case I prefer:
if ($_POST['submit']) {}
But here I get the PHP notice.
So which way is the most proper/accepted?
Thank you
回答1:
isset($_POST['submit'])
checks if the submit
key is set in the $_POST
array. It doesn't just check whether the $_POST
array exists and is therefore not "pointless". If you want to check whether the value is not falsey (== false
), which includes 0
, without triggering an error, that's what empty
is for:
if (!empty($_POST['submit']))
which is the same thing as
if ($_POST['submit'])
but without triggering a notice should the value not exist.
See The Definitive Guide To PHP's isset And empty for an exhaustive explanation.
回答2:
Try
if ($_SERVER['REQUEST_METHOD']=='POST')
{
//do
}
回答3:
As per my understanding, It should be like below:
if (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST'){
# if method is post, code goes here.
}
and if you are sure that your method is POST for sure. and you have data post in $_POST
you can use code like below:
if (isset($_POST['submit']) && $_POST['submit'] != '') {# I think, '' instead of 0
# if data is posted, code goes here.
}
I usually prefer $_POST
.
回答4:
$_POST[] checks to see if a variable is submitted and not the form name.
if ( isset($_POST['name']) ) {
// work here
}
来源:https://stackoverflow.com/questions/20491538/php-proper-check-if-postvariable-is-posted