Reputation: 645
I have foreach loop that looks like this:
foreach($wdata->query->pages->$wpageid->images as $iimages)
{
$name = $iimages->title;
$filename = str_replace(" ", "_",$name);
$filename = str_replace("File:","",$filename);
$digest = md5($filename);
$folder = $digest[0].'/'.$digest[0].$digest[1].'/'. $filename;
$url = 'http://upload.wikimedia.org/wikipedia/commons/'.$folder;
echo "<img style='height:100px;' src='$url'>";
}
It displayes images from a returned json array ($wdata) However, some images have been moved, or don't exist anymore, and I get cracked images, does anyone know how to check if an image is real, exists and can be viewed before it is echoed
Upvotes: 0
Views: 3195
Reputation: 9918
It is a remote file and file_exists()
does not work for this circumstance. So I suggest you to use getimagesize()
function which returns an array if the image exists.
<?php
$imageSize=getimagesize($url);
if(!is_array($imageSize))
{
echo "<img style='height:100px;' src='$url'>";
}
else
{
echo "no image";
}
?>
Another solution:
if (true === file_get_contents($url,0,null,0,1))
{
echo "<img style='height:100px;' src='$url'>";
}
This is faster because it tries to read only one byte of the file if exists.
Upvotes: 0
Reputation: 13525
Use a function as below and pass your url for test
if (image_exist($url)) {
echo "<img ...";
}
function image_exist($url) {
$file_headers = @get_headers($url);
if($file_headers[0] == 'HTTP/1.1 200 Found') {
return true;
}
return false;
}
Upvotes: -1
Reputation: 9034
Use the file_get_cotents()
function to check if it's there
if (file_get_contents("http://....") !== false) { //display image }
Upvotes: 2