get_meta_tags()连接被拒绝

问题描述:

在我的php代码中,我使用get_meta_tags()从网站获取元信息。但我的代理服务器拒绝连接,我收到以下错误:get_meta_tags()连接被拒绝

Warning:get_meta_tags(http://www.espncricinfo.com/)[function.get-meta-tags]:未能打开流:没有连接,因为目标机器积极拒绝它

任何人都可以告诉我如何通过代理在我的PHP代码?

我尝试在Eclipse XDebug配置中设置代理,但我不认为这是正确的方式来做到这一点。

curl我指定的代理为curl_setopt($ch, CURLOPT_PROXY, "host:port");哪些工作正常,但在PHP中我不知道该过程。 任何帮助,将不胜感激。

-Adithya

默认情况下PHP不使用代理。要绕过代理服务器,您可以使用http stream wrapper Docs(该包装程序正在照顾“文件名”,以http://https://开头)为您的所有功能添加代理,就像您在get_meta_tagsDocs函数示例中一样。

有很多HTTP context options Docs,你正在寻找的是proxy

由于get_meta_tags不接受上下文参数(仅一个文件名参数),您需要更改所使用的PHP函数接受一个文件名参数,该参数(一般)所谓默认情况下。它的设置为stream_context_get_defaultDocs

$opts = array(
    'http' => array(
     'proxy' => 'tcp://127.0.0.1:8000' 
    ) 
); 
stream_context_get_default($opts); 

不幸的是get_meta_tags看起来像一个例外的一般规则在所有使用流包装(至少我的PHP 5.3.8版本)。但不用担心,您可以使用默认上下文将您想要获取元标记的数据放入get_meta_tags

这可以通过data:// stream wrapperDocs完成。小助手功能,需要照顾的转换:

/** 
* obtain $filename content as data:// URI 
* 
* @link http://php.net/manual/en/wrappers.data.php 
* 
* @param string $filename 
* @return string data:// URI 
*/ 
function filename_data_uri($filename) 
{ 
    $buffer = file_get_contents($filename); 

    $mime = 'text/plain'; 
    # obtain mime type and charset from http response (if available) 
    if (isset($http_response_header)) 
     foreach($http_response_header as $header) 
      sscanf($header, 'Content-Type: %[^]]', $mime) 
    ; 

    return "data://$mime;base64,".base64_encode($buffer);  
}; 

这个功能可以从file_get_contents的URL,这使得使用默认的流上下文得到内容。这是代理配置的那个。

然后,您可以用get_meta_tags结合本:

$url = 'http://www.espncricinfo.com/'; 
$url = filename_data_uri($url); 
$meta_tags = get_meta_tags($url); 

get_meta_tags现在经营上一直取已经与filename_data_uri功能同时使用代理的$url内容。完整的例子:

$url = 'http://www.espncricinfo.com/'; 
$proxy = 'tcp://host:port'; 

// configure default context to use proxy 
$opts['http']['proxy'] = $proxy; 
$resource = stream_context_get_default($opts); 

// obtain url contents with default context 
$data = filename_data_uri($url); 
$meta_tags = get_meta_tags($data); 
print_r($meta_tags); 

/** 
* obtain $filename content as data:// URI 
* 
* @link http://php.net/manual/en/wrappers.data.php 
* 
* @param string $filename 
* @return string data:// URI 
*/ 
function filename_data_uri($filename) 
{ 
    $buffer = file_get_contents($filename); 

    $mime = 'text/plain'; 
    # obtain mime type and charset from http response (if available) 
    if (isset($http_response_header)) 
     foreach($http_response_header as $header) 
      sscanf($header, 'Content-Type: %[^]]', $mime) 
    ; 

    return "data://$mime;base64,".base64_encode($buffer);  
}; 
+0

我试过你的代码,但这也没有帮助!我收到以下错误: 警告:file_get_contents(http://www.espncricinfo.com/)[function.file-get-contents]:无法打开流:HTTP请求失败! HTTP/1.1 502代理错误(统一资源定位符(URL)不使用公认的协议。 我能够使用curl(通过配置代理)来获取网站内容,我试图将它传递给get_meta_tags函数,但这并不起作用。我读了get_meta_tags也接受了一个字符串,但没有奏效。 $ buffer始终为假。 – Adithya

+0

有没有办法在http头中指定协议? – Adithya