Verifying File Existence from a URL
Having trouble verifying file existence on a remote server using traditional file system functions? Don't worry, there's an alternative approach that's both quick and efficient.
Using get_headers()
PHP's get_headers() function allows you to retrieve the HTTP response headers for a given URL. When checking file existence, you're interested in whether the server responds with a 200 OK status code, indicating the presence of the file.
Code Example
Here's an example function to check file existence:
function file_exists_url($url){
$headers=get_headers($url);
return stripos($headers[0],"200 OK")?true:false;
}
Usage
You can use the function like this:
if(file_exists_url("http://www.example.com/file.txt"))
echo "File exists";
else
echo "File does not exist";
Advantages
This method is more efficient than using CURL, which can be an overkill for simply checking file existence. It also doesn't require any PHP extensions or external libraries.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3