1

I am working on an API of sorts. Its kinda like a RESTful API minus the put/delete currently. Works with GET/POST or the hope is that it will.

My issue is currently I don't want to have mirror code if at all possible where one acts based on POST and one acts based on GET where both are literally the same code otherwise.

So what I am trying to figure out is there a solution I can use to work with POST/GET data where I can use the same code base but not have to make one copy for $_GET and another for $_POST?

I know I can do something like

if($_POST)
{
//then work with the post data
}
if($_GET)
{
//then work with the get data
}

but the problem is obvious with this method, maybe im just not thinking far enough outside of the box so I dunno.. ideas?

chris
  • 36,115
  • 52
  • 143
  • 252
  • 1
    If you want to treat them synonymous(?) then `$_REQUEST` would be a better choice. With current configurations it's usually `$_REQUEST = array_merge($_POST, $_GET);` – mario Mar 03 '12 at 09:52

5 Answers5

5

Yes, You can create a generic function for this.

function doOperation($var)
{
   //then work with the var data
}

if(isset($_POST))
{
   doOperation($_POST);
}

if(isset($_GET))
{
   doOperation($_GET);
}
Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
  • Both `$_GET` and `$_POST` were set when I used this simple script: ``, even when no data was posted and no query string was used. – Salman A Mar 03 '12 at 10:39
  • @SalmanA Use specific data within without isset(), $_POST['something']. – Secko Mar 03 '12 at 10:45
3

You could use $_REQUEST.

casablanca
  • 69,683
  • 7
  • 133
  • 150
  • However, $_REQUEST also contains cookie data so you'd probably want to prevent that. Read this: http://devlog.info/2010/02/04/why-php-request-array-is-dangerous/ – Andy Mar 03 '12 at 09:56
  • 2
    @Andy: True, but the comments on the PHP manual page indicate that recent versions of PHP disable the cookie portion by default. – casablanca Mar 03 '12 at 09:57
2

Define a function that accepts an array of parameters:

function process($params)
{
  //then work with the params
}

then call that like so:

if(isset($_POST))
{
  process($_POST);
}
if(isset($_GET))
{
  process($_GET);
}
Andy
  • 8,870
  • 1
  • 31
  • 39
2

You can use $_SERVER["REQUEST_METHOD"] to determine whether your script was called via HTTP GET or POST method. Now assuming that you've coded your entire script to use $_GET you can copy all post variables to get variables:

if($_SERVER["REQUEST_METHOD"] == "POST") {
$_GET = $_POST;
}
Salman A
  • 262,204
  • 82
  • 430
  • 521
0

That's easy.
The code acts based on POST and one acts based on GET will never be the same.

  • GET is used to request data from the server.
  • POST is used to modify data on the server.

that's different codes and they never interfere

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345