WordPress Code Snippets

A fresh mix of code snippets and tutorials

PHP check if file exists by URL

260

This quick PHP snippet can be used to check if a specific URL exists. I use this in one of my projects for checking the existence of a robots.txt file on the site. Can be modified to check for files on any publicly accessible site.

Here is how this works:

  1. Sets three variables: $protocol, $robots, and $exists
  2. Check if PHP’s curl is available; if so, then use it to check for the specified URL ($robots variable)
  3. Check if get_headers is available; if so, then use it to check for the specified URL ($robots variable)

So the end result of this script will be that the $exists variable will return as true if the specified file/URL exists. Otherwise $exists remains false.

Notes: If WordPress is not available, you’ll need to modify or remove the $protocol variable accordingly. Also may want to change the $robots variable throughout depending on usage. And lastly, make sure to specify the URL of whichever resource/file you want to check.


Show Support

Like our new Facebook Page to show support!