LoginSignup
1
0

More than 5 years have passed since last update.

[php] 外部API呼び出しブラウザで見れるのにfile_get_contentsで呼ぶとWarningとなる

Last updated at Posted at 2019-02-15

前置き

外部APIを呼び出す実装を行う際に、用意されていたサーバーのモジュールがバラバラでcurlが使用できない条件だったので、file_get_contentsを使用し外部APIで呼び出すのにハマったのでメモ的に記載しておく。

環境は
php7.2 fuelphp1.8

ハマりどこ

ブラウザでたたくときちんとJSONコードが返ってくるが、file_get_contentsで呼び出すと、下記Warningが出てしまった。

Fuel\Core\PhpErrorException [ Warning ]:
file_get_contents(http://hogehoge/auth/login): failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized

結果

file_get_contents の第三引数に渡すコンテキストリソースを作成して渡すことで解決しました。

こんな感じです。

qiita.rb
$url = 'http://hogehoge/auth/login';
$context = stream_context_create(array(
 'http' => array('ignore_errors' => true)
));
echo file_get_contents($url, false, $context);

参考にさせて頂いたサイト。ありがとうございます!
Data API を PHP の file_get_contents で取得するときに注意した方がいいかもしれないこと
[メモ] PHPのfile_get_contentsを、HTTPリクエストに使うときのTIPS

ちなみに...

file_get_contents の頭に「@」を付けて「@file_get_contents」にすれば、Warning はでなくなったのですが、根本は解決しませんでした。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0