PHP判断远程文件是否存在的几种方法
代码如下:
0102030405060708091011121314151617181920212223242526272829303132333435 //方法一function
file_exists($url){$ch
= curl_init();curl_setopt($ch,
curlopt_url,$url);curl_setopt($ch,
curlopt_nobody, 1); //
不下载curl_setopt($ch,
curlopt_failonerror, 1);curl_setopt($ch,
curlopt_returntransfer, 1); if(curl_exec($ch)!==false)return
true;elsereturn
false;} //方法二function
file_exists2($url){if(file_get_contents($url,0,null,0,1))return
1;elsereturn
0;}//方法三function
file_exists($url)
{$curl
= curl_init($url);//
不取回数据curl_setopt($curl,
CURLOPT_NOBODY, true);//
发送请求$result
= curl_exec($curl);$found
= false;//
如果请求没有发送失败if
($result
!== false) {//
再检查http响应码是否为200}
方法一无论图片在不在都是返回FALSE;
方法二windows下可行,LINUX下无论图片在不在都返加TRUE;
方法三应该是最合适的
另外:用get_headers() 方法存在效率问题,建议不使用作为此解决方案
fsockopen版:
01020304050607080910111213141516171819 $url
= "https://www.baidu.com/img/baidu_sylogo1.gif"; $info
= parse_url($url); $fp
= fsockopen($info['host'],
80,$errno,
$errstr,
30); fputs($fp,"GET
{$info['path']} HTTP/1.1\r\n"); fputs($fp,
"Host:
{$info['host']}\r\n"); fputs($fp,
"Connection:
close\r\n\r\n"); $headers
= array(); while(!feof($fp))
{ $line
= fgets($fp); if($line
!= "\r\n")
{ $headers[]
= $line; }else
{ break; } } echo
"<pre>"; print_r($headers);
通过http状态码来判断文件是否存在,比如,响应 302,301,404等都为不存在,如果是200,304,等可以视为文件存在。
fopen()方法:
010203040506070809101112 <?php $url
= 'https://www.test.com/images/test.jpg'; if(
@fopen(
$url,
'r'
) ) { echo
'File Exits'; } else { echo
'File Do Not Exits'; } ?>
CURL 方法:
01020304050607080910111213141516 <?php $url2
= 'https://www.test.com/test.jpg'; $ch
= curl_init(); $timeout
= 10; curl_setopt
($ch,
CURLOPT_URL, $url2); curl_setopt($ch,
CURLOPT_HEADER, 1); curl_setopt
($ch,
CURLOPT_RETURNTRANSFER, 1); curl_setopt
($ch,
CURLOPT_CONNECTTIMEOUT, $timeout); $contents
= curl_exec($ch); //echo
$contents; if
(preg_match("/404/",
$contents)){ echo
'文件不存在'; }