Use php get_headers to determine if URL is an effective solution

  • 2020-06-01 08:40:57
  • OfStack

To determine the existence of a file or directory in php, is_file and file_exists are two functions that you usually think of. However, these two functions will still have some problems in determining whether a remote url file exists or not. Here the author will share with you a way to use the php get_headers function to determine whether a remote url file is valid or not.

For the function php get_headers and its usage, please refer to the following articles:

The function get_headers in php and its usage are introduced in detail

Here's how to use php get_headers to determine the true effectiveness of url.

Through the introduction of this function, we can know that this function simply says that it returns the header file information requested by 1 HTTP, and the information format is basically as follows:

(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
)

From the above two cases, it is easy to see that if the url is valid or not, it must be determined by the value of the first element in the array. When the server returns 200, it means the file is returned correctly, and when the server returns 404, it means the file does not exist. Therefore, it is easy to judge whether an url exists or not from this point.

(full source: PHP programmer notes)


Related articles: