HOWTO · PHP

PHP 代理

本教程演示如何在 PHP 中使用 cUrl 建立代理。

本頁內容

PHP 中的代理是通過 cURL 庫建立的。cURL 表示客戶端 URL 是 php 中最強大的擴充套件之一。

Denial Stenberg 建立了 cURL 庫來在不同伺服器之間進行通訊。

cURL 具有可以通過不同的 IP 和埠傳送請求的功能。cUrl 允許我們通過 URL 傳送和接收資料。

本教程演示如何在 PHP 中啟用 cURL 並使用 cURL 建立代理。

在 PHP 中啟用 cURL 庫

在開始建立代理之前,我們需要啟用 cURL 庫。cURL 庫已經存在於 PHP 中,我們必須啟用它。

首先,我們需要檢查是否啟用了 cUrl。建立一個 info.php 檔案並執行它。

<?php
    phpinfo();
?>

當你執行這個檔案時,它會顯示 PHP 的所有資訊。在進行下一步之前,有必要為 PHP 設定 PATH 變數。

如果已設定,則可以繼續。在 info.php 上搜尋 cURL。

如果未啟用,請轉到 PHP 主資料夾並找到 php.ini 檔案。最有可能的路徑是 C:\php74\php.ini。

使用文字編輯器開啟 php.ini 檔案。搜尋 curl,你會發現類似這樣的內容:

;extension=php_curl.dll

或者對於較新的 PHP 版本:

;extension=curl

現在刪除 ; 在擴充套件之前。儲存 php.ini 檔案並退出,重新啟動你正在使用的伺服器或本地主機。

extension=curl

再次執行 info.php 並搜尋 cURL support。你會看見:

cURL support: enabled

這意味著 cURL 已啟用,你可以開始了。如果 cURL 仍未啟用,請在擴充套件後嘗試 php_curl.dll 的絕對路徑。

extension=C:/php74/ext/php_curl.dll

使用 cURL 和 PHP 建立代理

cURL 有許多不同的關鍵字用於不同的操作。讓我們看一個為給定 URL 建立代理請求的示例:

//URL you want to apply cURL proxy.
$site = 'http://google.com';

// The Proxy IP address
$proxy_ip = '138.117.84.240';

//The proxy port.
$proxy_port = '999';

//Authentication information for proxy, username and password.
$Username = 'demouser';
$Password = 'demopassword';

//Initiate cURL response
$curl_reponse = curl_init($site);
curl_setopt($curl_reponse, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_reponse, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl_reponse, CURLOPT_HTTPPROXYTUNNEL , 1);

//Setting the IP address for proxy.
curl_setopt($curl_reponse, CURLOPT_PROXY, $proxy_ip);

//Setting the port for proxy.
curl_setopt($curl_reponse, CURLOPT_PROXYPORT, $proxy_port);

//Specifying the authentication information.
curl_setopt($curl_reponse, CURLOPT_PROXYUSERPWD, "$Username:$Password");

//Define the proxy server type, it is not neccessary, incase there is proxy connection aborted error. 
//The defaults type is CURLPROXY_HTTP, and the other options are CURLPROXY_SOCKS4, CURLPROXY_SOCKS4A, CURLPROXY_SOCKS5,and CURLPROXY_SOCKS5_HOSTNAME.
curl_setopt($curl_reponse, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);

//Execute the proxy request.
$output = curl_exec($curl_reponse);

//All the errors with number are given at this link from PHP Manual https://www.php.net/manual/en/function.curl-errno.php
//Error Number
echo curl_errno($curl_reponse).'<br/>';
// Error Info
echo curl_error($curl_reponse).'<br/>';

//Show the output, Return a cURL handle on success, and FALSE if there is an error.
echo $output;

上面的程式碼是建立代理請求以執行 google.com 的設定。該程式碼使用代理身份驗證。

代理不需要連線到給定的 IP 和埠。如果代理連線成功,它將返回 true 或 cURL 控制代碼。

如果有任何錯誤,它將列印錯誤號和資訊並返回 false。請參閱輸出以瞭解最常見的錯誤之一:

28
Failed to connect to 138.117.84.240 port 999: Timed out

這個錯誤主要是因為 IP 和埠。