If you want to access the API with PHP, wouldn't file_get_contents be enough?
table of contents
Hello.
I'm Mandai, in charge of Wild on the development team.
Do you know the PHP file_get_contents method?
I think this method is useful because the file opening process can be written concisely, but in addition to reading files, this method can also be used as a simple web access tool.
Today I would like to investigate the limits of how far this area can be used.
Basics of file_get_contents
As a simple example, to obtain our company's top page, the following sources would be used.
<?php $html = file_get_contents('https://beyondjapan.com');
I don't think this is a problem.
If this does not work, please check that the allow_url_fopen item in php.ini is as follows.
allow_url_fopen = On
Application of file_get_contents
The file_get_contents method is not only capable of getting HTML.
Next, try sending a POST using the stream_context_create method.
If you look at the manual for the stream_context_create method, it only says "creates a stream context".
By manipulating this stream context, you will be able to send POST.
<?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);
Use http_build_query to URL-encode and convert the query string for the data you want to send by POST.
In the case of JSON data, after passing it through the json_encode method, it is URL encoded using the urlencode method.
The true value of file_get_contents
You can create header information in the stream context, so as shown in the previous example, you can also create cookies as you wish!
You can also break through basic authentication and crawl sites using sessions.
It is also compatible with APIs that embed the API KEY in header information, such as Chatwork API.
If you want to use SSL communication, there is no need to think about it; just specify "https://" as the protocol.
Also, this is what I wanted to say, which is why 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 functional.)
That's it.