Model.request - kouji6309/SingleMVC GitHub Wiki
對指定網址做請求,可用來下載或上傳資料。
protected static request(
string $url,
string $method = 'get',
mixed $data = [],
array $option = [],
bool $get_header = false
) : mixed
-
請求路徑。
此數值將會設定CURLOPT_URL
。 -
請求方法,一般使用
GET
、POST
、PUT
、DELETE
、OPTIONS
。
此數值將會設定CURLOPT_CUSTOMREQUEST
。 -
輸入資料,會根據
method
與option['Header']['Content-Type']
不同而有所處理。 -
設定選項,可用以下索引名稱:
Header
:指定傳送的頭欄位,會套用curl_setopt($ch, CURLOPT_HTTPHEADER, $key.': '.$val)
。
Option
:curl 設定,會套用curl_setopt_array($ch, $option)
,詳細項目參考 PHP文件。以下是為方便使用,額外提出可設定的欄位,會覆蓋使用
Header
和Option
的設定:
User-Agent
:指定用戶代理。
Cookie
:指定要送出的 Cookie 內容。
Cookie-File
:若有定義 COOKIE_DIR,則會在下面建立以此為名的 Cookie 檔案。
SSL-Verify
:是否要驗證 SSL 憑證。
Proxy
:指定 Proxy 伺服器,如127.0.0.1:8888
。
HTTP-Version
:指定 HTTP 版本。 -
是否傳回 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');
}