file_exists():检查文件或目录是否存在。它一般只能用于检查本地的目录或文件,如果开发中,需要判断远程文件是否存在来进行对应的操作,那如何判断呢?

利用php5(低版本的好像不支持)中的get_headers()可以做到这一点,先让咱们看看它的格式语法及功能描述:


get_headers($string   [,format]): 取得服务器响应一个 HTTP 请求所发送的所有标头.

结果是返回一个数组,包含有服务器响应一个 HTTP 请求所发送的标头。如果失败则返回 FALSE 并发出一条 E_WARNING 级别的错误信息。如果将可选的 format 参数设为 1,则 get_headers() 会将解析相应的信息设定为数组的键名。

返回结果类似如下:


Array
(
 [0] => HTTP/1.1 200 OK
 [1] =>  Date: Sat, 29 May 2004 12:28:13 GMT
 [2] => Server: Apache/1.3.27 (Unix)   (Red-Hat/Linux)
 [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55  GMT
 [4] => ETag: "3f80f-1b6-3e1cb03b"
 [5] => Accept-Ranges:  bytes
 [6] => Content-Length: 438
 [7] => Connection: close
 [8] => Content-Type: text/html
)

如果有设第二个参数,结果类似如:


Array
(
 [0] => HTTP/1.1 200 OK
 [Date] => Sat, 29 May 2004  12:28:14 GMT
 [Server] => Apache/1.3.27 (Unix)  (Red-Hat/Linux)
 [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
 [ETag] =>  "3f80f-1b6-3e1cb03b"
 [Accept-Ranges] => bytes
 [Content-Length]  => 438
 [Connection] => close
 [Content-Type] =>  text/html
)

分析上面的两种输出,两种输出结果都表明远程文件存在,哪一句可以看出?

熟悉HTTP协议的朋友都知道,HTTP/1.1 200 OK 这句表明,HTTP请求响应的状态码为200,这表明请求成功!所以只要我们判断这个返回结果的arr[0]元素是否存在200字符串即可。我的写法如下:


function HttpFile_Exists($url){
       $status = '200';
       $FileArr = get_headers($url,1);
       if(stripos($FileArr[0],$status)){
               return true;
       }else{
               return false;
       }
}

5 Comments

  1. Hello there! Thanks a lot for a superb piece of content. My partner and i been recently struggling with here precisely what made you author this one blog content? Anyways,have a wonderful evening and thanks a bunch yet again for a very good read.

  2. Hi folks! Thanks for a impressive write up. I just was basically itching to know here what exactly made you compose this particular web log article? Whatever the case,have a wonderful day and many thanks again for a very good read.

  3. I love what you guys are consistently up too. Such clever work and reporting! Keep up the wonderful works guys I’ve added you guys to my blogroll. My best wishes, Elsy.

  4. A colleague of mine and I have spoken of this subject matter. Your blog posting help settled our challenge. I am going to continue reading more content! With thanks.

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


*