您好,登錄后才能下訂單哦!
在PHP中,cURL是一個強大的工具,用于發送和接收HTTP請求。以下是一些cURL的高級用法:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-Custom-Header: CustomValue',
'Authorization: Bearer YOUR_ACCESS_TOKEN'
));
$response = curl_exec($ch);
curl_close($ch);
CURLOPT_FOLLOWLOCATION
選項:$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com/redirect');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0); // 禁用重定向
$response = curl_exec($ch);
curl_close($ch);
CURLOPT_POSTFIELDS
選項發送數據:$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com/api');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
$response = curl_exec($ch);
curl_close($ch);
CURLOPT_UPLOAD
選項,并通過CURLOPT_POSTFIELDS
發送文件數據:$ch = curl_init();
$filePath = '/path/to/your/file.txt';
$fileName = basename($filePath);
curl_setopt($ch, CURLOPT_URL, 'https://example.com/upload');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, new CURLFile($filePath, 'text/plain', $fileName));
$response = curl_exec($ch);
curl_close($ch);
CURLOPT_TIMEOUT
選項設置請求的超時時間(以秒為單位):$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 設置超時為5秒
$response = curl_exec($ch);
curl_close($ch);
json_decode
函數將響應數據轉換為PHP對象或數組:$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true); // 將第二個參數設置為true以將結果轉換為關聯數組
$urls = [
'https://example.com/request1',
'https://example.com/request2',
'https://example.com/request3'
];
$mh = curl_multi_init();
$ch = [];
foreach ($urls as $i => $url) {
$ch[$i] = curl_init($url);
curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle($mh, $ch[$i]);
}
$stillRunning = null;
do {
curl_multi_exec($mh, $stillRunning);
} while ($stillRunning > 0);
foreach ($ch as $curl) {
$response = curl_multi_getcontent($curl);
echo "Response from $url: $response\n";
curl_multi_remove_handle($mh, $curl);
curl_close($curl);
}
curl_multi_close($mh);
這些只是cURL的一些高級用法。cURL提供了許多其他選項和功能,可以根據需要進行配置和使用。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。