문제

I have a page with a form. Which of the following methods is the best to use to check if the form is submitted? And how are they different?

Method 1:

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    //some code
}

Method 2:

if(isset($_POST['submit'])){
    //some code
}

Method 3 (obviously if I add submitted=true on submit to the query string):

if($_GET['submitted'] == true){
    //some code
}
도움이 되었습니까?

해결책

The method 1 and method 2 are the most appropriate ones.

If you validate the form using a $_GET['submitted'] == true this could easily be cracked by the end user which creates a security breach.

The best method i think is the first one

if($_SERVER['REQUEST_METHOD'] == 'POST')

This piece of code works good even on dynamically generated forms wherein you do not have to check a post variable.

다른 팁

In general if POST action then simply use

if (!empty($_POST))

If you're trying to post a form, then you should always use the appropriate HTTP request, POST. Furthermore, in most cases, it probably makes sense to check explicitly for a posted key, as you may have multiple forms on your page. Here's a break down of your methods. The second approach seems the best.:


if($_SERVER['REQUEST_METHOD'] == 'POST')

Check the see if the request method was of type POST. Not checking for data of any specific type.

if(isset($_POST['submit']))

Check to see if the key submit has been posted to the server.

if($_GET['submitted'] == true)

Check to see if the get parameter submitted, assumed to be set, is equal to true


See the difference between GET and POST for more. Specifically when it comes to posting forms, you should be aware of cross-site request forgery.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top