If you want to call an API using PHP, wouldn't file_get_contents be fine?

Hello,
I'm Mandai, the Wild Team member of the development team.

Are you familiar with the PHP method file_get_contents?
It's a useful method because it allows you to write file opening processes succinctly, but this method can also be used as a simple web access tool in addition to reading files.
Today, I'd like to investigate the limits of its usefulness.

 

file_get_contents basics

As a simple example, to get our company's homepage, the source would look like this:

<?php $html = file_get_contents('https://beyondjapan.com');


 This should be fine.
If this doesn't work, make sure your php.ini file allows_url_fopen:

allow_url_fopen = On

 

Application of file_get_contents

The file_get_contents method can do more than just get HTML.
Next, let's try sending a POST using the stream_context_create method.

If you look at the manual for the stream_context_create method, it simply says "Create a stream context."
By manipulating this stream context, you can send POSTs.

<?php $data = [ 'title' =>'Send test', 'body' => 'test', ]; $opts = [ 'http' => [ 'method' => 'POST', 'header' => implode("\r\n", [ "User-Agent: hogehoge", "Accept-Language: ja", "Cookie: test=hoge", ]), ], 'data' => http_build_query($data) ]; $ctx = stream_context_create($opts); $response = file_get_contents('http://example.com/inquiry', false, $ctx);


 The data you want to send via POST should be URL-encoded and converted to a query string using http_build_query.
For JSON data, you should pass it through the json_encode method and then URL-encode it using the urlencode method.

 

The true value of file_get_contents

As shown in the previous example, you can create header information in the stream context, so you can use cookies as you like!
You can also bypass basic authentication and browse sites using sessions.

It also supports APIs that embed the API key in the header information, such as Chatwork API

If you want to use SSL communication, you don't need to think about it too much; just specify "https://" as the protocol

And that's what I wanted to say, so I wrote this blog

file_get_contents works even in environments where php-curl is not installed, so it can be used as an alternative to the curl library
(of course, curl is more powerful)

 
That's all

If you found this article useful, please click [Like]!
2
Loading...
2 votes, average: 1.00 / 12
15,875
X Facebook Hatena Bookmark pocket

The person who wrote this article

About the author

Yoichi Bandai

My main job is developing web APIs for social games, but I'm also grateful to be able to do a variety of other work, including marketing.
My portrait rights within Beyond are CC0.