Model.request - kouji6309/SingleMVC GitHub Wiki

說明

對指定網址做請求,可用來下載或上傳資料。


原型

protected static request(
    string $url,
    string $method = 'get',
    mixed $data = [],
    array $option = [],
    bool $get_header = false
) : mixed

參數

  • url

    請求路徑。
    此數值將會設定 CURLOPT_URL

  • method

    請求方法,一般使用 GETPOSTPUTDELETEOPTIONS
    此數值將會設定 CURLOPT_CUSTOMREQUEST

  • data

    輸入資料,會根據 methodoption['Header']['Content-Type'] 不同而有所處理。

  • option

    設定選項,可用以下索引名稱:
    Header:指定傳送的頭欄位,會套用 curl_setopt($ch, CURLOPT_HTTPHEADER, $key.': '.$val)
    Option:curl 設定,會套用 curl_setopt_array($ch, $option),詳細項目參考 PHP文件

    以下是為方便使用,額外提出可設定的欄位,會覆蓋使用 HeaderOption 的設定:
    User-Agent:指定用戶代理。
    Cookie:指定要送出的 Cookie 內容。
    Cookie-File:若有定義 COOKIE_DIR,則會在下面建立以此為名的 Cookie 檔案。
    SSL-Verify:是否要驗證 SSL 憑證。
    Proxy:指定 Proxy 伺服器,如 127.0.0.1:8888
    HTTP-Version:指定 HTTP 版本。

  • get_header

    是否傳回 Header,是則將結果結構改為

    ['header' => [ ... ], 'content' => '...']

回應

  • 布林:false,執行失敗。
  • 字串:請求結果的內容。
  • 陣列:請求結果的頭欄位與內容。

應用

取得指定網址的資料

$result = self::request('https://www.example.com/');

傳送資料到指定路徑

$data = [
    'username' => 'user',
    'password' => 'Passw0rd',
];
$result = self::request('https://www.example.com/api/login', 'post', $data);

傳送 JSON 資料到指定路徑

$data = [
    'username' => 'user',
    'password' => 'Passw0rd',
];
$result = self::request('https://www.example.com/api/login', 'post', $data, [
    'Header' => [
        'Content-Type' => 'application/json',
    ],
]);

取得指定網址的頭欄位與資料

$result = self::request('https://www.example.com/api/login', 'get', null, null, true);
if ($result['header']['Status'] == 200) {
    $content = $result['content'];
} else {
    throw new Exception('Error');
}
⚠️ **GitHub.com Fallback** ⚠️