A
A
Araik2019-12-04 12:07:35
PHP
Araik, 2019-12-04 12:07:35

How to make a POST request via file_get_contents?

Why POST request with Curl works, but not with file_get_contents?
I do this with Curl:

<?php
  $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
      curl_setopt($curl, CURLOPT_POST, 1);
      curl_setopt($curl, CURLOPT_POSTFIELDS, $requestParams);

      $result = curl_exec($curl);
      curl_close($curl);
      
      $response = new \RegRuAPI\Response($result);

Everything is ok with this, it works as it should.
with file_get_contents I do this:
$context = stream_context_create(array(
      'http' => array(
            'method' => 'POST',
            'header' => 'Content-Type: application/x-www-form-urlencoded' . PHP_EOL,
            'content' => $requestParams,
      ),
    ));
  
    $result = file_get_contents($url, false, $context);

The request goes, but the transferred data is not taken into account, I get an error:
object(RegRuAPI\Response)#7 (4) {
  ["status"]=>
  string(5) "error"
  ["error_code"]=>
  string(7) "NO_AUTH"
  ["error_text"]=>
  string(35) "No authorization mechanism selected"
  ["error_params"]=>
  object(stdClass)#9 (1) {
    ["command_name"]=>
    string(13) "domain/create"
  }
}

In both cases, the parameter array looks like this:
array(6) {
  ["show_input_params"]=>
  int(0)
  ["input_format"]=>
  string(4) "json"
  ["output_format"]=>
  string(4) "json"
  ["io_encoding"]=>
  string(4) "utf8"
  ["lang"]=>
  string(2) "ru"
  ["input_data"]=>
  string(54) "{"currency":"RUR","username":"test","password":"test"}"
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanatPHP, 2019-12-04
@NinjaNickName

context must be a string, not an array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question