Php 检查文件是否存在于不同的域中,而不读取它
有没有比这更好的方法来检查文件是否存在(它位于不同的域上,因此文件_exists无法工作)Php 检查文件是否存在于不同的域中,而不读取它,php,Php,有没有比这更好的方法来检查文件是否存在(它位于不同的域上,因此文件_exists无法工作) $fp = fsockopen($fileUri, 80, $errno, $errstr, 30); if (!$fp) { // file exists } fclose($fp); 看到这个和解释了吗 $url = "http://www.example.com/index.php"; $header_response = get_headers($url, 1); if ( strpos
$fp = fsockopen($fileUri, 80, $errno, $errstr, 30);
if (!$fp) {
// file exists
}
fclose($fp);
看到这个和解释了吗
$url = "http://www.example.com/index.php";
$header_response = get_headers($url, 1);
if ( strpos( $header_response[0], "404" ) !== false )
{
// FILE DOES NOT EXIST
}
else
{
// FILE EXISTS!!
}
或
将maxlength设置为1您可以使用curl并检查标题中的响应代码 有几个例子你可以使用
使用curl时,使用curl_setopt将CURLOPT_NOBODY切换为true,这样它只下载头文件,而不下载完整文件。例如,
curl\u setopt($ch,CURLOPT\u NOBODY,true)代码>我确实喜欢这个。它总是很好:
$url = "http://www.example.com/index.php";
$header_response = get_headers($url, 1);
if ( strpos( $header_response[0], "404" ) !== false )
{
// FILE DOES NOT EXIST
}
else
{
// FILE EXISTS!!
}
那怎么办
<?php
$a = file_get_contents('http://mydomain.com/test.html');
if ($a) echo('exists'); else echo('not exists');
来自
我的所有测试都表明它可以按预期工作。我将使用curl来检查标题,并验证内容类型
比如:
function ExternalFileExists($location,$misc_content_type = false)
{
$curl = curl_init($location);
curl_setopt($curl,CURLOPT_NOBODY,true);
curl_setopt($curl,CURLOPT_HEADER,true);
curl_exec($curl);
$info = curl_getinfo($curl);
if((int)$info['http_code'] >= 200 && (int)$info['http_code'] <= 206)
{
//Response says ok.
if($misc_content_type !== false)
{
return strpos($info['content_type'],$misc_content_type);
}
return true;
}
return false;
}
或者,如果您对分机不确定,那么:
if(ExternalFileExists('http://server.com/file.ext'))
{
}
他确实说过他不想要这些内容,但我只是检查一下它是否存在,如果文件只有几GB怎么办?你说得对。然后最好使用CURL和setopt只获取标题查看我使用maxlength参数的答案如果文件存在但长度为0字节,这将不起作用。get_headers比CURL慢,我认为。事实证明,CURL库比常规php函数响应更快,传输数据更快,这就是为什么我认为get_头会更慢。我没有证据,只是我在地方、论坛等中所读到的,我会考虑将第3行更改为<代码>(StrupS($HealthReal[Re](0),“200”)==false)< /C> >因此,403个拒绝访问的文件没有被有效地返回。谢谢。现在我已经使用了Alexander的解决方案(它只是我应用程序中的一个地方),但如果我需要在我的应用程序中的几个地方检查外部文件,我可能会使用你的函数。你最好的构建一个curl库,它可以发送(get/post)接收(headers/html/files),还可以与DOMDocument
交互。这样,您就可以在1个lib内获得所需的一切。
function ExternalFileExists($location,$misc_content_type = false)
{
$curl = curl_init($location);
curl_setopt($curl,CURLOPT_NOBODY,true);
curl_setopt($curl,CURLOPT_HEADER,true);
curl_exec($curl);
$info = curl_getinfo($curl);
if((int)$info['http_code'] >= 200 && (int)$info['http_code'] <= 206)
{
//Response says ok.
if($misc_content_type !== false)
{
return strpos($info['content_type'],$misc_content_type);
}
return true;
}
return false;
}
if(ExternalFileExists('http://server.com/file.avi','video'))
{
}
if(ExternalFileExists('http://server.com/file.ext'))
{
}