Andrii Tarykin
Andrii Tarykin

Reputation: 628

Can't send data in post request via file_get_contents

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.

Upvotes: 0

Views: 11663

Answers (2)

Lajos Veres
Lajos Veres

Reputation: 13725

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?

Upvotes: 4

Elon Than
Elon Than

Reputation: 9775

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").

Upvotes: 1

Related Questions