Skip to content
Advertisement

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement