2

I am using curl to call API method (Symfony2, FOSRestBundle) and wonder how can I get the data sent in POSTFIELDS?

    $_params = [];
    $data_string = json_encode($_params);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $_method);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($curl, CURLOPT_VERBOSE, true);

    $json = curl_exec($curl);

If I send something in for example CURLOPT_HTTPHEADER I can get it later in controller using

$request->headers->get("some_variable");

But how can I access $data_string? I have dumped almost every possible variable and still nothing.

cyberbrain
  • 3,433
  • 1
  • 12
  • 22
Ridley
  • 21
  • 1
  • 4

2 Answers2

0

To retrieve a POST value in symphony you can use:

$request->request->get('key', 'default value');

Assuming $_params is a valid json object, you need to url-ify the data for the POST, i.e.:

$post_fields = http_build_query(json_decode($_params));
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_fields); </s>

To retrieve all post values in symphony you can use:

$params = $this->getRequest()->request->all();
$params['val1'];
$params['val2'];
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • 2
    That's correct, but i need to get all POST variables send with CURL. I mean i need to retrevie value of variable $data_string. – Ridley Oct 07 '15 at 11:26
  • I have updated my question a little bit. My problem is that i need to access $data_string variable in a controller, when $_params is an array (sometimes empty, sometimes contains some keys and values) – Ridley Oct 07 '15 at 11:43
0

As I understand your first code snippet, you're effectively trying to POST a JSON string? It was my understanding that your PHP code wouldn't work as per the PHP documentation for CURLOPT_POSTFIELDS:

This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value.

But as per this blog post apparently you can do it your way.

Anyway, back to your question. To get the full content of a request, you would do:

$content = $request->getContent();

And to then decode the JSON you would do:

$params = json_decode($content);

Another StackOverflow answer covers this. About the only thing I'd say is that you need to correctly set the MIME type when you're sending the post, e.g.

curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json' ]);

The previously mentioned blog post covers this.

Community
  • 1
  • 1
John Noel
  • 1,401
  • 10
  • 13