使用php get_headers 判断URL是否有效的解决办法_php实例

WBOY
Release: 2016-06-07 17:24:46
Original
797 people have browsed it

在php中判断一个文件或目录是否存在,大家通常都会想到is_file和file_exists两个函数。但这两个函数再判断一个远程url文件是否存在的问题上还是会存在这样那样的问题。这里作者将和大家分享一种利用php get_headers函数来判断远程url文件是有效否存在的办法。

关于php get_headers函数的作用及用法,可以参考本站文章:

php中get_headers函数的作用及用法的详细介绍

下面来具体说如何利用php get_headers却判断url的真实有效性。

通过该函数的介绍,我们可以知道对于这个函数简单的说就是它返回的是一个HTTP请求的头文件信息,信息格式基本如下:

(1)

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
)

(2)

Array
(
    [0] => HTTP/1.0 404 Not Found
    [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
)

从以上两种情况可以很容易看出,如果判断该url是否有效存在肯定是通过数组中的第一个元素值来判断的。服务器返回 200 即文件正确返回的意思,服务器返回 404 即文件不存在,因此从这个地方就可以很容易的判断一个url的是否存在了。

(详细出处:PHP程序员笔记)

 

Related labels:
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!