Paul
Paul

Reputation: 11746

PHP $_POST, $_GET, or $_REQUEST

I have a functions file where I handle POST and GETS letting the user perform either a post or a get. It's more like an API call.

Should I be doing it like this or would using $_REQUEST handle both a POST and a GET?

if ($_SERVER['REQUEST_METHOD'] === "GET") {

    $function = $_GET['f'];
    $user_id  = $_GET['user_id'];
}
elseif ($_SERVER['REQUEST_METHOD'] === "POST") {

    $function = $_POST['f'];
    $user_id  = $_POST['user_id'];
}

$res = new stdClass();

if (isset($function)) {

    switch ($function) {    
         ....
    }
}

Upvotes: 0

Views: 1740

Answers (5)

Yuda Prawira
Yuda Prawira

Reputation: 12461

Yes you can, $_REQUEST handles both $_POST and $_GET.

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116110

If you want to allow both, you can just use $_REQUEST. It's much easier if you don't care whether the value was POSTed or -er- GETted. Note, though, that $_REQUEST may contain cookies as well, based on settings in PHP.ini.

Upvotes: 3

Luke
Luke

Reputation: 14128

$_REQUEST can be both $_POST and $_GET, but it can also be $_COOKIE as well, depending on the request_order or variables_order settings. Because it can also be neither of these depending on an ini setting, I wouldn't use it at all.

My recommendation is use $_GET and $_POST separately. They mean completely different things. You want to use a $_POST for an action, and a $_GET for fetching. If you want form filling based on $_GET you can use $_SERVER['REQUEST_METHOD'] == 'POST' to determine what is actually happening and toggle between the two.

Upvotes: 1

Harshal
Harshal

Reputation: 3622

$_REQUEST is the most convenient way to handle the both type of request ($_GET & $_POST). So use the $_REQUEST :

REQUEST METHOD IN PHP

Upvotes: 0

Robert DeBoer
Robert DeBoer

Reputation: 1695

The benefit that your current approach offers it that you can use the best method for each instance. There are some times when you would not want to GET since it just appends the data to the URL, exposing it to anyone who looks as well as exposing that "call" to anyone who knows how to use URLs for bad things.

If you are worried about catching calls that you not not be able to controll the request method, you could add the $_REQUEST as a last resort but I would suggest limiting what you use that for - example: just pulling data from the DB and not anything that modifies it.

Upvotes: 4

Related Questions