Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

php - isset($_POST['submit']) vs $_SERVER['REQUEST_METHOD']=='POST'

I have come across scripts that use:

isset($_POST['submit'])

as well as code that uses:

$_SERVER['REQUEST_METHOD']=='POST'

I was wondering the difference between these two and which method is best.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
isset($_POST['submit']) 

If you already know that a particular value will always be sent and therefore is indicative of an expected form submission (the submit field in this case) this code will tell you two things:

  1. The form is submitted via the POST method, as opposed to GET, PUT, etc.
  2. The submit field has been passed.

$_SERVER['REQUEST_METHOD'] == 'POST'

This tells you exactly one thing, a form was submitted via the POST method. Reasons to use it include:

  • You want to distinguish between an invalid form submission (e.g. not all fields were transmitted) and other kinds of page retrieval (GET, PUT, etc.)
  • You don't know exactly what you're going to receive. Perhaps this code is run in a controller which doesn't know all details of its dependent parts.

The former is

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!isset($_POST['name'])) {
        // at this point you know that `name` was not passed as part of the request
        // this could be treated as an error
    }
}

Versus:

if (!isset($_POST['name'])) {
    // the `name` field was not passed as part of the request
    // but it might also be a GET request, in which case a page should be shown
}

Important

Checking for a submit button field in the request is not reliable as a form can be submitted in other ways (such as pressing Enter in a text box).


$_POST

By just using this expression you can assert that:

  1. The form is submitted via POST
  2. At least one field has been submitted

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...