1

根据服务器配置,我通常会使用两种方法来远程检查使用 PHP 的 CDN 托管脚本的可用性。一个是cURL,另一个是fopen。我结合了我在各自情况下使用的两个函数,如下所示:

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
   }
}

...但我不想重新发明轮子。这是一种好的、可靠的技术,还是任何人都可以提供有关如何简化/简化流程的指示?

4

1 回答 1

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() 会更快,因为它是一个内置函数,而不必加载诸如 cURL 之类的 PECL 扩展。至于 fopen() 你需要做的任务是检查响应头,get_headers() 的唯一用途就是这样做,fopen() 无法获取头,cURL 还有其他用途更不用说不必要的了开销并且不专注于获取标头,因此在这种情况下使用它是最合适的选择。

于 2012-12-12T06:57:58.827 回答