如何在PHP中設(shè)置SOCKS5代理超時(shí)

PHP
小樊
82
2024-08-29 11:56:12

要在 PHP 中使用 SOCKS5 代理并設(shè)置超時(shí),您可以使用 cURL 庫(kù)

<?php
// 目標(biāo) URL
$url = "http://example.com";

// 代理服務(wù)器的 IP 和端口
$proxy_host = "127.0.0.1";
$proxy_port = 1080;

// 設(shè)置超時(shí)(單位:秒)
$timeout = 10;

// 初始化 cURL 會(huì)話
$ch = curl_init();

// 設(shè)置 cURL 選項(xiàng)
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

// 設(shè)置代理類型為 SOCKS5
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
curl_setopt($ch, CURLOPT_PROXY, $proxy_host . ":" . $proxy_port);

// 執(zhí)行 cURL 請(qǐng)求
$response = curl_exec($ch);

// 檢查是否有錯(cuò)誤
if (curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
} else {
    echo $response;
}

// 關(guān)閉 cURL 會(huì)話
curl_close($ch);
?>

這段代碼首先初始化一個(gè) cURL 會(huì)話,然后設(shè)置目標(biāo) URL、代理類型和代理服務(wù)器。接下來(lái),它設(shè)置超時(shí)值(單位:秒),然后執(zhí)行請(qǐng)求。最后,它檢查是否有錯(cuò)誤并輸出結(jié)果。

注意:確保您已經(jīng)安裝了 PHP 的 cURL 擴(kuò)展。如果沒(méi)有安裝,請(qǐng)根據(jù)您的系統(tǒng)環(huán)境安裝相應(yīng)的擴(kuò)展。

0