
在PHP 中使用cURL 最佳化HTTP 回應碼擷取
要增強cURL 在擷取HTTP 狀態碼時的效能,至關重要實作最有效的做法。這可以透過以下方式實現:
驗證 URL:
在啟動 cURL 請求之前,請先驗證 URL 以確保其完整性。這可以防止不必要的請求並提高效能。
1 2 3 | <code class = "php" > if (! $url || ! is_string ( $url ) || !preg_match( '/^http(s)?:\/\/[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i' , $url )) {
return false;
}</code>
|
登入後複製
僅檢索標頭:
要減少網路開銷,請將 cURL 配置為僅檢索 HTTP 標頭,忽略不必要的正文內容。
1 2 | <code class = "php" >curl_setopt( $ch , CURLOPT_HEADER, true);
curl_setopt( $ch , CURLOPT_NOBODY, true);
|
登入後複製
其他最佳化:
請參閱先前的討論以進行進一步最佳化,特別是在處理 URL 重定向時。
組合這些策略,這是程式碼片段的最佳化版本:
1 2 3 4 5 6 7 8 9 10 11 | <code class = "php" > $url = 'http://www.example.com' ;
$ch = curl_init( $url );
curl_setopt( $ch , CURLOPT_HEADER, true);
curl_setopt( $ch , CURLOPT_NOBODY, true);
curl_setopt( $ch , CURLOPT_RETURNTRANSFER, 1);
curl_setopt( $ch , CURLOPT_TIMEOUT, 10);
$output = curl_exec( $ch );
$httpcode = curl_getinfo( $ch , CURLINFO_HTTP_CODE);
curl_close( $ch );
echo 'HTTP code: ' . $httpcode ;</code>
|
登入後複製
透過實作這些最佳化,您可以顯著提高基於 cURL 的 HTTP 回應程式碼擷取的效能和效率。
以上是如何在 PHP 中使用 cURL 最佳化 HTTP 回應碼檢索?的詳細內容。更多資訊請關注PHP中文網其他相關文章!