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

table of contents
Hello.
I'm Mandai, the Wild team member in charge of development.
Are you familiar with PHP's `file_get_contents` method?
It's a very useful method because it allows you to write file opening code concisely, but this method can also be used as a simple web access tool.
Today, I'd like to investigate the limits of how far this can be used.
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, check if the allow_url_fopen entry in php.ini is set to the following.
allow_url_fopen = On
Application of file_get_contents
The `file_get_contents` method isn't limited to just retrieving HTML.
Next, let's try sending a POST request using the `stream_context_create` method.
Looking at the manual for the `stream_context_create` method, it simply says, "Creates a stream context."
By manipulating this stream context, you can send POST requests.
<?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);
For data you want to send via POST, you should pre-encode it using http_build_query and convert it to a query string.
For JSON data, you would first pass it through the json_encode method, and then URL encode it using the urlencode method.
The true value of file_get_contents
Since you can create header information in a stream context, as shown in the previous example, you can manipulate cookies as you like!
You can also bypass basic authentication and crawl 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, it goes without saying that curl is more feature-rich.)
That's all
2
