0

Need to request some code two times in my app. Fist request url as ajax call, and also need to request this url in controller (something like hmvc). I know how to develop this via curl but I found another kind of idea how to implement this, just use function file_get_contents with before prepared params. This my code:

    // Setup limit per page
    $args['offset'] = $offset;
    $args['limit']  = $this->_perpage;
    // --

    // Convert search arguments to the uri format
    $data = http_build_query($args);

    // Define request params
    $options = array(
        'http' => array(
            'header'  => 'Content-type: application/json' . PHP_EOL .
                         'Content-Length: ' . strlen($data) . PHP_EOL,
            'method'  => 'POST',
            'content' => $data,
        ),
    );

    $context = stream_context_create($options);

    $result  = file_get_contents(
        'http://'.$_SERVER['HTTP_HOST'].'/search/items', FALSE, $context
    );

Request method was detected ok in requested uri, but params wasn't passed. Why this is not pass arguments to request? Where is bug in my code? Many thanks for any answers.

Andrii Tarykin
  • 568
  • 2
  • 6
  • 24

2 Answers2

4

http_build_query builds application/x-www-form-urlencoded content. (not application/json)

There is a full example:

How to post data in PHP using file_get_contents?

Community
  • 1
  • 1
Lajos Veres
  • 13,186
  • 7
  • 39
  • 56
1

Content type should be application/x-www-form-urlencoded. If you want to stay with application/json, try to get posted data using file_get_contents("php://input").

Elon Than
  • 8,984
  • 4
  • 22
  • 37