在我的php代码中,我使用get_meta_tags()
从网站获取元信息。但是我的代理服务器拒绝连接,我得到以下错误:
警告:get_meta_tags(http://www.espncricinfo.com/) [function。get-meta-tags]: failed to open stream:由于目标机器主动拒绝,无法建立连接
谁能告诉我如何通过代理在我的php代码?
我尝试在Eclipse XDebug配置中设置代理,但我不认为这是正确的方法。
在curl
中,我指定代理为curl_setopt($ch, CURLOPT_PROXY, "host:port");
,它工作得很好,但在php中,我不知道该过程。如有任何帮助,不胜感激。
-Adithya
默认情况下PHP不使用代理。为了绕过代理,您可以使用http流包装器Docs为所有函数添加代理(该包装器正在处理以http://
或https://
开头的"文件名"),就像您的get_meta_tags
Docs函数示例一样。
有很多HTTP上下文选项Docs,你要找的是proxy
。
由于get_meta_tags
不接受上下文参数(仅接受文件名参数),因此需要更改所谓的默认上下文,该上下文(通常)由接受文件名参数的PHP函数使用。设置为stream_context_get_default
Docs。
$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://
流包装器Docs来完成。一个小的辅助函数负责转换:
/**
* 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
现在对$url
的内容进行操作,这些内容已经在使用代理时通过filename_data_uri
函数获取。完整的示例:
$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);
};