0

I'm working on a web library for personal use. I thought I'd be all clever and use variable variables to make my library support all request methods easily.

I had:

$request = '_' . $_SERVER['REQUEST_METHOD'];
$request = $$request;

But I get:

Undefined variable: _POST

Printed to my php error log.

I was just curious as to whether my idea is flawed conceptially, as well as why the logic fails to work when the following does:

$_a = 'b';
$b = '_a';
$c = $$b;

Edit:

The following does work:

$request = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;

Duplicate of: Superglobals can't be accessed via variable variables in a function?

To fix I did:

$request = $GLOBALS['_' . $_SERVER['REQUEST_METHOD']];

You could also use my original code outside of a function or class.

Community
  • 1
  • 1
csga5000
  • 4,062
  • 4
  • 39
  • 52
  • Why do you use ninja code? – VeeeneX Feb 16 '15 at 10:32
  • 1
    possible duplicate of [Superglobals can't be accessed via variable variables in a function?](http://stackoverflow.com/q/8071118/1503018) – sectus Feb 16 '15 at 10:43
  • @VeeeneX I was using this code to support multiple request methods. Primarily GET and POST, I don't know that this would work for PATCH/PUT/DELETE, etc. Note my recent answer which probably is a better way to do it – csga5000 Apr 04 '16 at 19:04

2 Answers2

0

The error message you are getting is correct, there is no such variable as $_POST.

$request = '_' . $_SERVER['REQUEST_METHOD'];

Let's assume $_SERVER['REQUEST_METHOD'] is "POST" which it will be for an HTTP POST request.

Therefore $request == "_POST"

$request = $$request;

i.e. $request = $_POST;

What is it exactly you're trying to achieve here?

delatbabel
  • 3,601
  • 24
  • 29
  • @deltababel The reason I was doing this magically was so the server worked for multiple request methods. Ex. get and post – csga5000 Apr 04 '16 at 19:05
0

To made it work as I said in my post:

$request = $GLOBALS['_' . $_SERVER['REQUEST_METHOD']];

Why?

Because $_POST and $_GET are global variables and need to accessed as such. Inside functions/classes you would usually do something like:

global $_POST;

before using.

You could also use the original code outside of a function or class.

Better way in this case?

My intention with this was to support multiple request methods. I don't thing that this would work for PUT/PATCH/DELETE etc. I would advise instead you use:

$requestdata = fopen("php://input", "r");

See: http://php.net/manual/en/features.file-upload.put-method.php

This may not work for url parameters only request body. Not sure. (If this is the case then for get REQUESTS you'd want to use $_GET

csga5000
  • 4,062
  • 4
  • 39
  • 52