您好,登錄后才能下訂單哦!
在PHP中,cURL是一個強(qiáng)大的工具,用于發(fā)送和接收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
選項(xiàng):$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
選項(xiàng)發(fā)送數(shù)據(jù):$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
選項(xiàng),并通過CURLOPT_POSTFIELDS
發(fā)送文件數(shù)據(jù):$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
選項(xiàng)設(shè)置請求的超時時間(以秒為單位):$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 設(shè)置超時為5秒
$response = curl_exec($ch);
curl_close($ch);
json_decode
函數(shù)將響應(yīng)數(shù)據(jù)轉(zhuǎn)換為PHP對象或數(shù)組:$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); // 將第二個參數(shù)設(shè)置為true以將結(jié)果轉(zhuǎn)換為關(guān)聯(lián)數(shù)組
$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提供了許多其他選項(xiàng)和功能,可以根據(jù)需要進(jìn)行配置和使用。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。