Check file for presence / existence
Sometimes we display content from other resources on sites: images 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 you check the existence of a file using PHP?
There is a file_exists () function , but it is only good for files within our file system, and it won’t work with a remote server.
There is an option to open the file for reading and, in case of an error, to state the fact that the file does not exist: However, this technique takes a lot of time. There is an even better option - use the get_headers () function : it makes a request to the file and receives all the headers with the answer in approximately this array
As we can see, there is a response code in the zero element, 200 means that the file exists, and we can easily access it.
Here is the code that will verify the existence of the file. Now, let's compare two methods in time with the existing favicon and with the nonexistent one: with a nonexistent file, the second method (get_headers) wins for two hundredths of a second. with an existing file, both methods showed approximately the same time.
There is a file_exists () function , but it is only good for files within our file system, and it won’t work with a remote server.
There is an option to open the file for reading and, in case of an error, to state the fact that the file does not exist: However, this technique takes a lot of time. There is an even better option - use the get_headers () function : it makes a request to the file and receives all the headers with the answer in approximately this array
// файл, который мы проверяем
$url = "http://url.to/favicon.ico";
// пробуем открыть файл для чтения
if (@fopen($url, "r")) {
echo "Файл существует";
} else {
echo "Файл не найден";
}
?>
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 can see, there is a response code in the zero element, 200 means that the file exists, and we can easily access it.
Here is the code that will verify the existence of the file. Now, let's compare two methods in time with the existing favicon and with the nonexistent one: with a nonexistent file, the second method (get_headers) wins for two hundredths of a second. with an existing file, both methods showed approximately the same time.
// файл, который мы проверяем
$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 "Файл не найден";
}
?>