user8949562
user8949562

Reputation:

What does this $_SERVER['REQUEST_METHOD'] === 'POST' do?

A little new to php and reading some people's code and saw this:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['...'])) {

        } else {
            echo "...";
        }
    }

I get what isset(...) is doing but don't understand the what the first if statement. Especially because the if statement was working when my request method was GET but wasn't when my request method was POST

Upvotes: 4

Views: 22102

Answers (3)

Clint
Clint

Reputation: 1073

I suspect you are inadvertently resubmitting the data when you refresh the page to view it.

Hence, the post data is present again.

Try placing the cursor at the end of the URL in the browser and hit 'enter'

Upvotes: 0

James
James

Reputation: 4783

$_SERVER['REQUEST_METHOD'] is one of the PHP server variables.

It determines:

Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.

It's generally defaulted to GET though, so don't rely on it for determining if a form has been posted or not (eg if not POST then must be GET etc).

 

You said:

the if statement was working when my request method was GET but wasn't when my request method was POST

I can't see why that would be the case, you must have had something else different, or possibly caching/browser history was at play.

Upvotes: 2

L1R
L1R

Reputation: 225

say your page is called yourpage.php -- What that code means is that the portion of code in the IF statement will ONLY be run if you are accessing yourPage.php page via Posting a form. So if you just load that page normally, by typing yourpage.php in the address bar. that code will not run.

But if you have some < form action='yourPage.php' >. When you submit that form, and you come to yourpage.php That code will run only in that instance. When the page has come via posting.

Its basically a way to ensure that certain code will only happen AFTER the posting of the form, think of a message like "Thanks for filling out our survey!" which pops up after you submit your form only, but still on the same page.

Upvotes: 5

Related Questions