Checking Existence of Files from URLs
Determining the existence of a file hosted on a remote server can be a common requirement. While the often-used functions is_file() and file_exists() may not suffice in this scenario, there's an alternative approach that leverages PHP's get_headers function.
By utilizing get_headers, you can retrieve HTTP response headers for the specified URL. These headers provide information about the file's availability and status. Specifically, you need to examine the value of the $result[0] element. If it includes "200 OK," it implies that the file is present on the server.
To facilitate this check, you can employ a custom function like this:
function UR_exists($url){ $headers=get_headers($url); return stripos($headers[0],"200 OK")?true:false; }
This function returns true if the HTTP response contains "200 OK" and false otherwise.
To test the existence of a URL, you can utilize the function as shown in the following example:
if(UR_exists("http://www.amazingjokes.com/")) echo "This page exists"; else echo "This page does not exist";
This approach provides a straightforward and efficient method to determine the presence of files from remote URLs without the need for additional dependencies like CURL, which could introduce unnecessary overhead.
The above is the detailed content of How to Check the Existence of Files on Remote Servers from URLs?. For more information, please follow other related articles on the PHP Chinese website!