时间:2021-07-01 10:21:17 帮助过:8人阅读
最简单的方法就是用fopen(),看看文件能否打开,能打就文件当然就存在。
<?php
$url = 'http://www.bitsCN.com/images/test.jpg';
if( @fopen( $url, 'r' ) )
{
echo 'File Exits';
}
else
{
echo 'File Do Not Exits';
}
?>
方法二:
/** * 筛选不存在的图片资源 * * @author wanggeng* @return vodi */ private static function _checkAll($url) { $curl = curl_init($url); curl_setopt($curl, CURLOPT_NOBODY, true); $result = false; $res = curl_exec($curl); if ($res !== false){ $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); if($statusCode == 200) { $result = true; } } curl_close($curl); return $result; }
首先建立一个curl链接到执行的url也就是图片或者文件的链接
初始一个变量为false
或者打开链接的head头信息 每一个http请求都会有一个http Code
我们就根据这个code去验证
如果返回code 是200 证明资源存在 给之前的变量一个true的值 否则不予赋值
方法三:
CURL 方法
CURL是个很好用的类库,下面看下如何用它来判断。
<?php
$url2 = 'http://www.bitsCN.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 '文件不存在';
}
?>
curl_exec()执行完之后如果文件不存在,会返回如下信息:
HTTP/1.1 404 Not Found Date: Tue, 14 Feb 2012 05:08:34 GMT Server: Apache Accept-Ranges: bytes Content-Length: 354 Content-Type: text/html
用正则看看是否有404,有的话文件就不存在。
以上所述就是本文的全部内容了,希望大家能够喜欢。