I am trying to fetch image from few external sites as I’m trying to develop link sharing website for my project. I downloaded file with curl to local server but getimagesize is still very slow (30 seconds). I’m a newbie to php any help would be appreciated. Here is the code:
function check_url($value)
{
$value = trim($value);
if (get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
$value = strtr($value, array_flip(get_html_translation_table(HTML_ENTITIES)));
$value = strip_tags($value);
$value = htmlspecialchars($value);
return $value;
}
$curl = curl_init();
$temp_file = tempnam(sys_get_temp_dir(), 'link');
$fp = fopen($temp_file, "w");
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_FILE, $fp);
curl_exec ($curl);
curl_close($curl);
///
$html = file_get_contents($temp_file);
fclose ($fp);
unlink($temp_file);
if($html) {
//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
//get and display what you need:
$title = $nodes->item(0)->nodeValue;
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++)
{
$meta = $metas->item($i);
if($meta->getAttribute('name') == 'description')
$description = $meta->getAttribute('content');
}
// fetch images
$image_regex = '/<img[^>]*'.'src=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($image_regex, $html, $img, PREG_PATTERN_ORDER);
$images_array = $img[1];
?>
<div class="images">
<?php
$k=1;
for ($i=0;$i<=sizeof($images_array);$i++)
{
if(@$images_array[$i])
{
if(@getimagesize(@$images_array[$i]))
{
list($width, $height, $type, $attr) = getimagesize(@$images_array[$i]);
if($width >= 80 && $height >= 80 ){
echo "<img src='".@$images_array[$i]."' width='100' id='".$k."' >";
$k++;
}
}
}
}
?>
<input type="hidden" name="total_images" id="total_images" value="<?php echo --$k?>" />
</div>
<div class="info">
<label class="title">
<?php echo @$title; ?>
</label>
<br clear="all" />
<label class="url">
<?php echo substr($url ,0,35); ?>
</label>
<br clear="all" /><br clear="all" />
<label class="desc">
<?php echo @$description; ?>
</label>
<br clear="all" /><br clear="all" />
<label style="float:left"><img src="prev.png" id="prev" alt="" /><img src="next.png" id="next" alt="" /></label>
<label class="totalimg">
Total <?php echo $k?> images
</label>
<br clear="all" />
</div>
<?php
} else {
echo "Please enter a valid url";
}
?>
This is not surprising. You are looping through all of those images. Downloading those images and then getting their sizes can take significant time.
At best, you can load those images asynchronously and cache results.