I’m working on an app that exports data to a KML file. It pulls the data from a database, then uses SimpleXML to write the file.
Some entities in the dataset have an associated image URL. As KML allows HTML in the descriptions, I’m adding the images to the description in <img>
tags.
But before I do, I would like to check the image URL, and only add it if the URL works.
My first attempt was with file_exists()
, but I found that unreliable, as it always seems to return false, so I get no pictures at all.
I did a bit of searching for other solutions.
This was a nice short one I found on SO:-
function url_exists($url) {
return curl_init($url) !== false;
}
It was very fast, like file_exists()
, but it seems also unreliable, as it was including broken URLs, which defeats the object of having a test.
I found some using @get_headers()
, Eg:-
// Initialize an URL to the variable
$url = "https://www.geeksforgeeks.org";
// Use get_headers() function
$headers = @get_headers($url);
// Use condition to check the existence of URL
if($headers && strpos( $headers[0], '200')) {
$status = "URL Exist";
}
else {
$status = "URL Doesn't Exist";
}
// Display result
echo($status);
And using curl:-
$url = "http://www.domain.com/demo.jpg";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_NOBODY, true);
$result = curl_exec($curl);
if ($result !== false)
{
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 404)
{
echo "URL Not Exists"
}
else
{
echo "URL Exists";
}
}
else
{
echo "URL not Exists";
}
Both of these appear to work, but I find they make things run quite slow.
I did slim them down a bit and wrap them in functions, but they are essentially what I tried. These are posted as copied.
Is it just a case of having to swallow the fact that I am at the mercy external server responses?
Or is there a reliable, fast way to get just enough info to say the URL is good, without downloading any image data at this time?