LoginSignup
3
5

More than 5 years have passed since last update.

【PHP】file_get_contents関数を使わずにAPIと通信する(curlでPOST)

Last updated at Posted at 2018-02-08

file_get_contents関数がつかえない

APIと通信する処理を実装するのにfile_get_contents関数を使ったらだめ(というか使えない)という規約にぶち当たった。
じゃあ何かほかに方法ないかな→curlでPOSTできるらしい
これ使うしかない

curlでPOSTする実装

例では、APIにPOSTするのはname項目という想定です。
(ちなみに想定しているAPIは自前スタブAPIです → 【PHP】とりあえずAPIのスタブをパパっと作る - Qiita

post.php
/**
 * URLに対してPOST送信しAPIからの値を取得する
 *
 * @param string $url
 * @return array
 */
function sendPostToApiByCurlAndRetrieveJson($url)
{
    $ch = curl_init($url);

    /* POSTする値 */
    $postParams = [
        'name' => 'POST_TEST',
    ];

    $postOption = [
        CURLOPT_POST           => true,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_POSTFIELDS     => http_build_query($postParams),
        CURLOPT_RETURNTRANSFER => true,
    ];

    curl_setopt_array($ch, $postOption );

    $content = curl_exec($ch); 
    $err     = curl_errno($ch); 
    $errmsg  = curl_error($ch);
    $header  = curl_getinfo($ch);

    curl_close($ch); // リソース開放

    /* errorチェック */
    if ($err !== 0) {
        if (isset($errmsg)) {
            return ['error' => $errmsg];    
        }
        return [];
    }

    if ($header['http_code'] !== 200) {
        if (isset($errmsg)) {
            return ['error' => $errmsg];    
        }
        return [];
    }

    return json_decode($content, true);
}

おわり

  • $postOptioの設定がぁゃιぃ
  • 関数名ながくない?ながいよね。ながいなぁ
  • タイプヒンティング書いてないのはPHP7で動かせないからです
  • Basic認証かかってるURLに対してPOSTする際はhttps://user:pass@*******/api.phpみたいに書かないとエラーが帰ってくるので注意

参考

3
5
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
3
5