加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

php判断远程文件是否存在的三种方法

发布时间:2020-05-25 02:13:11 所属栏目:PHP 来源:互联网
导读:php判断本地服务器文件是否存在可以使用file_exists函数,但是该函数不能用于判断远程文件是否存在,要判断远程文件是否存在,我们可以使用fopen()函数或curl或get_headers函数,本文章向大家介绍fopen()和curl判断远程文件是否存在的实例。

方法一:使用curl判断远程文件是否存在:

function remoteFileExists($url) {

$curl = curl_init($url);

//don't fetch the actual page,you only want to check the connection is ok

curl_setopt($curl,CURLOPT_NOBODY,true);

//do request

$result = curl_exec($curl);

$ret = false;

//if request did not fail

if ($result !== false) {

//if request was ok,check response code

$statusCode = curl_getinfo($curl,CURLINFO_HTTP_CODE);

if ($statusCode == 200) {

$ret = true;

}

}

curl_close($curl);

return $ret;

}

$exists = remoteFileExists('http://manongjc.com/favicon.ico');

if ($exists) {

echo '文件存在';

} else {

echo '文件不存在';

}

方法二:使用fopen()判断远程文件是否存在

$file = 'http://manongjc.com/favicon.ico';

$file_exists = (@fopen($file,"r")) ? true : false;

方法三:使用fopen()判断远程文件是否存在

function remote_file_exists($url){

return(bool)preg_match('~HTTP/1.ds+200s+OK~',@current(get_headers($url)));

}

/* http://www.manongjc.com/article/1415.html */

$ff = "http://manongjc.com/favicon.ico";

if(remote_file_exists($ff)){

echo "file exist!";

}

else{

echo "file not exist!!!";

}

function is_url($url)

{

$array= get_headers($url);

$h= $array[0];

return( strlen($h==3) && ($h[2]=='2' || $h[2]=='3'));

}

注意:上面三种方法都是判断HTTP状态码(并没有下载文件),这样效率更高。

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读