您好,欢迎访问一九零五行业门户网

使用PHP处理不存在的图片资源

如何使用php处理不存在的图片资源?本文给大家汇总了几个使用php实现筛选不存在图片资源的方法,非常的简单实用。希望对大家有所帮助。
方法一:
最简单的方法就是用fopen(),看看文件能否打开,能打就文件当然就存在。
<?php $url = 'http://www.jb51.net/images/test.jpg'; if( @fopen( $url, 'r' ) ) { echo 'file exits'; } else { echo 'file do not exits'; } ?>
方法二:
/** * 筛选不存在的图片资源 * * @author wanggeng <wanggeng123@vip.qq.com> * @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.jb51.net/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,有的话文件就不存在。
相关推荐:
php 远程下载图片到本地
php 远程文件管理,可以给表格排序,遍历目录,时间排序_php教程
【php curl类库】10个php curl类库下载
以上就是使用php处理不存在的图片资源的详细内容。
其它类似信息

推荐信息