📜 ⬆️ ⬇️

Check file for existence / existence

Sometimes we display content from other resources on sites: pictures or favicons. Some browsers will simply leave an empty space (Firefox), while others will display an ugly rectangle, clearly indicating that something is missing (IE). How can PHP tools verify the existence of a file?

There is a file_exists () function, but it is only good for files within our file system, and it will not work with a remote server.

There is an option to open the file for reading and, in case of an error, state the fact that the file does not exist:
<?
// ,
$url = "http://url.to/favicon.ico";

//
if (@fopen($url, "r")) {
echo " ";
} else {
echo " ";
}
?>

')
However, this technique takes a lot of time.

An even better option is to use the get_headers () function:
it makes a request to the file and gets all the headers with the answer approximately in such an array
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
)


As we see, in the zero element there is a response code, 200 means that the file exists, and we can easily access it.
Here is the code that will verify the existence of the file.

<?
// ,
$url = "http://url.to/favicon.ico";
$Headers = @get_headers($url);
// 200 -
//if(preg_match("|200|", $Headers[0])) { // - :)
if(strpos('200', $Headers[0])) {
echo " ";
} else {
echo " ";
}
?>


Now let's compare the two methods with the existing favicon and with the nonexistent one:
when a file does not exist, the second method (get_headers) wins by two hundredths of a second.
with the existing file, both methods showed approximately the same time.

Source: https://habr.com/ru/post/50846/


All Articles