2012-12-12 36 views
1

我通常運行兩種方法,這取決於服務器配置,它使用PHP遠程檢查CDN託管的腳本的可用性。一個是cURL,另一個是fopen。我結合這兩個功能我用在各自的情況下,像這樣:在WordPress中使用CDN託管腳本的單一功能

function use_cdn(){ 
    $url = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'; // the URL to check against 
    $ret = false; 
    if(function_exists('curl_init')) { 
     $curl = curl_init($url); 
     curl_setopt($curl, CURLOPT_NOBODY, true); 
     $result = curl_exec($curl); 
     if (($result !== false) && (curl_getinfo($curl, CURLINFO_HTTP_CODE) == 200)) $ret = true; 
     curl_close($curl); 
    } 
    else { 
     $ret = @fopen($url,'r'); 
    } 
    if($ret) { 
     wp_deregister_script('jquery'); // deregisters the default WordPress jQuery 
     wp_register_script('jquery', $url); // register the external file 
     wp_enqueue_script('jquery'); // enqueue the external file 
    } 
    else { 
     wp_enqueue_script('jquery'); // enqueue the local file 
    } 
} 

...但我不希望推倒重來。這是一個好的,堅實的技術,還是任何人都可以提供關於如何簡化/簡化流程的指針?

+0

我會很擔心,如果谷歌CDN崩潰,世界將會結束。 O.o –

+0

@cryptic我知道,但是Google不必因爲某些地區/某些網絡等原因而無法使用CDN。 –

+0

請看我的簡化方法。 –

回答

1

使用get_headers()我們可以發出一個HEAD請求並檢查響應代碼以查看該文件是否可用,並且還會允許我們查看網絡或DNS是否關閉,因爲它會導致get_headers()失敗(保留@符號來抑制PHP錯誤,如果域名無法解析,這將導致它在這種情況下返回FALSE,因此加載本地文件:

function use_cdn() 
{ 
    $url = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'; // the URL to check against 
    $online = FALSE; 

    if(function_exists('curl_init')) 
    { 
     $curl = curl_init($url); 
     curl_setopt($curl, CURLOPT_NOBODY, TRUE); 
     $result = curl_exec($curl); 
     if ((FALSE !== $result) && ('200' == curl_getinfo($curl, CURLINFO_HTTP_CODE))) 
     { 
      $online = TRUE; 
     } 
     curl_close($curl); 
    } 
    else if (ini_get('allow_url_fopen')) 
    { 
     stream_context_set_default(array('http' => array('method' => 'HEAD'))); // set as HEAD request 
     $headers = @get_headers($url, 1); // get HTTP response headers 
     if ($headers && FALSE !== strpos($headers[0], '200')) // if get_headers() passed and 200 OK 
     { 
      $online = TRUE; 
     } 
    } 

    if ($online) 
    { 
     wp_deregister_script('jquery'); // deregisters the default WordPress jQuery 
     wp_register_script('jquery', $url); // register the external file 
    } 
    wp_enqueue_script('jquery'); // enqueue registered files 
} 

get_headers()會更快,因爲它是在功能上構建,反對不得不加載一個PECL擴展,比如cURL。對於fopen(),你需要做的任務是檢查響應頭,get_headers()的唯一用處就是做這件事,fopen()不能獲取頭,cURL還有其他用途提到不必要的開銷,並且不專注於獲取標題,因此在這種情況下它將是最合適的選擇。

+0

我喜歡那樣。使用'get_headers()'而不是'fopen'或'cURL'有什麼好處?有沒有事實上的標準? –

+0

get_headers()會更快,因爲它是一個內置函數,與加載PECL擴展(如cURL)相反。至於fopen(),你需要做的任務是檢查響應頭信息,get_headers()的唯一用處就是做到這一點,fopen()不能獲取頭文件,而cURL有其他用途,不必提及不必要的開銷,並不專注於獲取標題,所以這將是在這種情況下使用最合適的選擇。 –

+0

嗯,太棒了!公認。也許在你的答案中加上一個註釋來解釋這些優點? –