Home > php教程 > php手册 > php筛选不存在的图片资源,

php筛选不存在的图片资源,

WBOY
Release: 2016-06-13 09:05:47
Original
855 people have browsed it

php筛选不存在的图片资源,

方法一:

最简单的方法就是用fopen(),看看文件能否打开,能打就文件当然就存在。

<&#63;php
$url = 'http://www.bkjia.com/images/test.jpg';

if( @fopen( $url, 'r' ) ) 
{ 
 echo 'File Exits';
} 
else 
{
 echo 'File Do Not Exits';
}
&#63;>

Copy after login

方法二:

/** 
   * 筛选不存在的图片资源 
   * 
   * @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; 
  } 
Copy after login

首先建立一个curl链接到执行的url也就是图片或者文件的链接
初始一个变量为false
或者打开链接的head头信息 每一个http请求都会有一个http Code
我们就根据这个code去验证
如果返回code 是200 证明资源存在 给之前的变量一个true的值 否则不予赋值

方法三:

CURL 方法

CURL是个很好用的类库,下面看下如何用它来判断。

<&#63;php
$url2 = 'http://www.bkjia.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 '文件不存在';
}
&#63;>

Copy after login

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
Copy after login

用正则看看是否有404,有的话文件就不存在。

以上所述就是本文的全部内容了,希望大家能够喜欢。

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template