我尝试检测流(ogg或mp3文件)是否存在。
我想使用get_headers,但是我注意到我的主机已经禁用了这个功能。
我可以在htaccess中激活它,但由于某些原因它不能正常工作。
无论如何,我决定使用cURL,如果我尝试检测url是否存在,它就会工作:
$curl = curl_init();
curl_setopt_array( $curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'http://stackoverflow.com' ) );
curl_exec( $curl );
$response_code = curl_getinfo( $curl, CURLINFO_HTTP_CODE );
curl_close( $curl );
echo 'http://stackoverflow.com : response code '.$response_code.'<br />';
if ($response_code == 200)
{
echo 'url exists';
} else {
echo "url doesn't exist";
}
很好。我尝试了一个错误的url,响应代码是0。
我不知道为什么它不能在我的流中工作,比如这个:
http://locus.creacast.com:9001/StBaume_grotte.ogg
我想到了一个服务器问题,但我已经尝试了在网络上发现的其他流(像这个:http://radio.rim952.fr:8000/stream.mp3),我仍然无法得到响应代码。
$curl_2 = curl_init();
curl_setopt_array( $curl_2, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => 'http://locus.creacast.com:9001/StBaume_grotte.ogg' ) );
curl_exec( $curl_2 );
$response_code_2 = curl_getinfo( $curl_2, CURLINFO_HTTP_CODE );
curl_close( $curl_2 );
echo '<br /><br />http://locus.creacast.com:9001/StBaume_grotte.ogg : '.$response_code_2.'<br />';
if ($response_code_2 == 200)
{
echo 'url existe';
} else {
echo "url n'existe pas";
}
所以我猜这不是服务器问题,而是与url/文件的类型有关。
你知道我可以查什么吗?我的响应代码总是0,即使文件存在,它是非常慢的获得响应代码。
您可以尝试使用以下代码来获取响应头。您可以为较慢的URL增加超时时间,但请记住,这也会影响您自己的页面加载。
$options['http'] = array(
'method' => "HEAD",
'follow_location' => 0,
'ignore_errors' => 1,
'timeout' => 0.2
);
$context = stream_context_create($options);
$body = file_get_contents($url, NULL, $context);
if (!empty($http_response_header))
{
//var_dump($http_response_header);
//to see what tou get back for usefull help
if (substr_count($http_response_header[0], ' 404')>0)
echo 'not found'
}
更新:我注意到问题出在身体上。看起来它试图下载所有东西,即使有一个HEAD请求。因此,我将请求更改为简单的fopen
,它可以工作。
<?php
$url = 'http://radio.rim952.fr:8000/stream.mp3';
// Try and open the remote stream
if (!$stream = @fopen($url, 'r')) {
// If opening failed, inform the client we have no content
if (!empty($http_response_header))
{
var_dump($http_response_header);
}
exit('Unable to open remote stream');
}
echo 'file exists';
?>
我用rim952 url进行了测试,因为其他url在firefox中甚至无法加载。我通过将请求更改为流进行测试。