384

Possible Duplicate:
PHP detecting request type (GET, POST, PUT or DELETE)

This should be an easy one.

I have a script, and in the script I want to determine whether the request arrive via GET or POST method.

What is the correct way to do it?

I am thinking of using something like this

if (isset($_POST)) {
    // do post
} else  {
    // do get
}

But deep in my heart I don't feel this is the right way. Any idea?

Community
  • 1
  • 1
Graviton
  • 81,782
  • 146
  • 424
  • 602
  • 2
    Why can't you try $_REQUEST["variable_name"] if you target processing variables regardless of request type? – Anoop Pete Jan 20 '16 at 16:58
  • 5
    @AnoopPete - because that's not what was being asked. $_REQUEST will accept GET, POST, PUT, DELETE (anything). Not only is this terrible practice, it can lead to security risks. Imagine your logic is simply expecting a form POST method, but you allow any/all methods to be accepted. That could have dire consequences in the wrong hands. – mferly Apr 04 '16 at 14:26
  • try using this it will help you wheather form is get or post if( $_REQUEST["name"] || $_REQUEST["age"] ) { echo "Welcome ". $_REQUEST['name']. "
    "; echo "You are ". $_REQUEST['age']. " years old."; exit(); }
    – sarvesh Jan 13 '18 at 09:24

2 Answers2

910

Better use $_SERVER['REQUEST_METHOD']:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // …
}
leek
  • 11,803
  • 8
  • 45
  • 61
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • @Gumbo does we need `===`, what will happen if I used `==` – Kasun Siyambalapitiya Sep 06 '16 at 10:36
  • 7
    You can use `===` *or* `==`. The former is just good practice, as it checks if the variables are 'identical'. (EG: `5 == '5'` is `true`, but `5 === '5'` is `false`) – Justin Sep 19 '16 at 22:41
  • 4
    Also consider returning 405 if it's neither GET nor POST. if ($_SERVER['REQUEST_METHOD'] === 'POST') { // do post } elseif ($_SERVER['REQUEST_METHOD'] === 'GET') { // do get } else { http_response_code(405); die(); } – Andrew Downes Jan 06 '17 at 18:20
  • 10
    According to NetBeans IDE, it's not good to access `$_SERVER` directly. So, in this case, the alternative is `if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') { … }`. – ban-geoengineering Apr 27 '17 at 12:51
  • I've experienced environments where PHP doesn't actively set the $_POST global, so I agree that using the above method works much more reliably. – Nathan Crause Jul 05 '17 at 15:52
  • @AndrewDownes as u mentioned to use `http_response_code(405);` under which circumstances this will occur. I tried removing method, but it takes default as GET – ajinzrathod Apr 13 '20 at 11:28
  • @ajinzrathod You can use also `PUT` or `DELETE` method – Sergio Diaz Apr 14 '21 at 11:58
80

Use $_SERVER['REQUEST_METHOD'].

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186