How can I check if the request is a post back in PHP, is the below ok?
if (isset($_POST["submit"]))
wh开发者_开发技巧ere submit
is the name
of the <input type="submit" />
That will work if you know and expect such a submit button on the same page.
If you don't immediately know anything about the request variables, another way is to check the request method:
if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST')
As pointed out in the comments, to specifically check for a postback and not just any POST request, you need to ensure that the referrer is the same page as the processing page. Something like this:
if (basename($_SERVER['HTTP_REFERER']) == $_SERVER['SCRIPT_NAME'])
You want $_SERVER['REQUEST_METHOD'] == 'POST'
.
Yours is a very similar although less general question than this one.
This is probably a better approach than actually checking a post variable. For one, you don't know whether that variable will be sent along. I have the hunch that some browsers just won't send the key at all if no value is specified. Also, I'd worry that some flavors of PHP might not define $_POST
if there are no POSTed values.
If you want to have a generic routine without dependency "method" (post/get) and any other names of the forum elements, then I recommend this
<?php
$isPostBack = false;
$referer = "";
$thisPage = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
if (isset($_SERVER['HTTP_REFERER'])){
$referer = $_SERVER['HTTP_REFERER'];
}
if ($referer == $thisPage){
$isPostBack = true;
}
?>
now the if $isPostBack will be true if it is a postback, false if not.
I hope this helps
Yes, that should do it.
Careful when you're using image
type submits, they won't send the name
attribute in some browsers and you won't be able to detect the POST. Smashed my head against the desk a few times until I realized it myself.
The workaround for that is to add a hidden
type input as well.
Yes. You could also use if(array_key_exists('submit', $_POST))
精彩评论