我尝试从网站上获取一些信息,然后将其称为x网站(http://212.237.41.34/player.php?ch=b3) 当我尝试从我的电脑连接该网站时,它会将我重定向到http://www.cndhlsstream.pw/网站。
这是我的问题;当我尝试使用curl或file_get_contents获取x站点的内容时,它仅返回"无效连接"。
我该如何解决这个问题?
我在x网站的底部看到有一个脚本
<script>
if (top.location == self.location) {
top.location = "http://www.cndhlsstream.pw/";
}
</script>
我认为这会导致此错误,但我无法解决问题。
我试试这个但它仍然会返回无效连接
$context = stream_context_create(
array(
'http' => array(
'follow_location' => false
)
)
);
echo file_get_contents('http://212.237.41.34/player.php?ch=b3',false,$context);
答案 0 :(得分:2)
默认情况下,curl和file_get_contents都不发送用户代理标头,也不发送Connection: keep-alive
。你的这个网站很奇怪,它需要一个用户代理,它需要标题Connection: keep-alive
,否则它会响应&#34;无效的连接&#34;,所以发送这两个标题以避免错误。这是curl的一个(工作)示例:
$ch = curl_init ();
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'http://212.237.41.34/player.php?ch=b3',
CURLOPT_HTTPHEADER => array (
'Connection: keep-alive' // the server will just say "invalid connect" unless this header is sent, no idea why
),
CURLOPT_USERAGENT => 'php/' . PHP_VERSION . ', libcurl/' . curl_version () ['version'], // without a useragent, the server will also say "invalid connect"
CURLOPT_ENCODING => '', // <<the server supports gzip, this will make the transfer compressed, making it much faster
CURLOPT_VERBOSE => true // <<makes curl print lots of useful debugging info
) );
curl_exec ( $ch );
curl_close( $ch );
还要注意curl比file_get_contents快,主要有两个原因,1:curl停止读取content-length
个字节,file_get_contents忽略这个标题,只是一直保持读取直到连接关闭,这可能会慢得多。 2:curl支持压缩传输(gzip和deflate),file_get_contents不支持,并且html压缩得非常非常好(在我跑回去的一些测试中,它比未压缩的对应物容易小3-5倍),并且curl_代码工作正常无论php.ini选项如何,而file_get_contents依赖于启用allow_url_fopen
php.ini选项。
答案 1 :(得分:0)
您需要为外部Web服务器指定用户代理以接受您的请求。
$context = stream_context_create([
'http' => [
'user_agent' => 'any'
]
]);
$output = file_get_contents('http://212.237.41.34/player.php?ch=b3', false, $context);
要阻止重定向,请使用str_replace
来解压缩命令。
$output = str_replace('top.location = "http://www.cndhlsstream.pw/";', '', $output);
var_dump($output);
答案 2 :(得分:-1)
$context = stream_context_create(
array(
'http' => array(
'follow_location' => false //dont not follow redirect
)
)
);
$html = file_get_contents('http://www.example.com/', false, $context);
var_dump($http_response_header);
参考:How do I ignore a moved-header with file_get_contents in PHP?