Reputation: 11
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
}
Upvotes: 1
Views: 660
Reputation: 9347
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.
Upvotes: 0
Reputation: 2728
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.
Upvotes: 6