LoginSignup
0
0

More than 5 years have passed since last update.

【PHP】cCRL関数でAPIを叩く

Posted at

前にも調べた気がする…と思ったら案の定だったので、手元に残しておこうと思った次第。

<?php

/**
 * APIを叩く(POST)
 *
 * @param string $url
 * @param array $params
 * @return array|bool
 */
function curl_post($url, $params) {
    $ch = curl_init($url);
    if (!$ch) {
        return false;
    }

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 証明書の検証をしたくない場合
    curl_setopt($ch, CURLOPT_TIMEOUT, 180);// 3分間待ってやる
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));
    curl_setopt($ch, CURLOPT_POST, true);// GETの場合→curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, false);

    $result = curl_exec($ch);
    if (!$result) {
        curl_close($ch);
        return false;
    }

    if (curl_errno($ch)) {
        curl_close($ch);
        return false;
    }

    $http_code = curl_get_info($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    if ($http_code != 200) {
        return false;
    }

    return json_decode($result, true);
}

?>

参考
PHP: 基本的な curl の使用法 - Manual
PHP: cURL 関数 - Manual
Send json post using php - Stack Overflow https://stackoverflow.com/questions/6213509/send-json-post-using-php
WebAPIを叩く(curl) https://qiita.com/re-24/items/bfdd533e5dacecd21a7a

※この記事は、アウトプットネタ棚卸し Advent Calendar 2018 17日目の記事です。

0
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
0
0