开发者

Checking if request is post back in PHP [duplicate]

开发者 https://www.devze.com 2023-01-26 01:02 出处:网络
This question already has answers here: Detecting request type in PHP (GET, POST, PUT or DELETE) (14 answers)
This question already has answers here: Detecting request type in PHP (GET, POST, PUT or DELETE) (14 answers) Closed 8 years ago.

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))

0

精彩评论

暂无评论...
验证码 换一张
取 消