1. 程式人生 > >分享一個PHP調用RestFul接口的函數

分享一個PHP調用RestFul接口的函數

new highlight ray 參數 true post string 分享 tran

/**
 * [http 調用接口函數]
 * @Date   2016-07-11
 * @Author GeorgeHao
 * @param  string       $url     [接口地址]
 * @param  array        $params  [數組]
 * @param  string       $method  [GET\POST\DELETE\PUT]
 * @param  array        $header  [HTTP頭信息]
 * @param  integer      $timeout [超時時間]
 * @return [type]                [接口返回數據]
 */
function http($url, $params, $method = ‘GET‘, $header = array(), $timeout = 5)
{
    // POST 提交方式的傳入 $set_params 必須是字符串形式
    $opts = array(
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => $header
    );

    /* 根據請求類型設置特定參數 */
    switch (strtoupper($method)) {
        case ‘GET‘:
            $opts[CURLOPT_URL] = $url . ‘?‘ . http_build_query($params);
            break;
        case ‘POST‘:
            $params = http_build_query($params);
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        case ‘DELETE‘:
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_HTTPHEADER] = array("X-HTTP-Method-Override: DELETE");
            $opts[CURLOPT_CUSTOMREQUEST] = ‘DELETE‘;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        case ‘PUT‘:
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 0;
            $opts[CURLOPT_CUSTOMREQUEST] = ‘PUT‘;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            throw new Exception(‘不支持的請求方式!‘);
    }
  
    /* 初始化並執行curl請求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data = curl_exec($ch);
    $error = curl_error($ch);
    return $data;
}

  

分享一個PHP調用RestFul接口的函數