Reputation: 4253
I have a function to check if image is valid, and if it is print the img on the screen.
<?php
function isImage($url){
$url_headers=get_headers($url, 1);
if($url_headers[0] == 'HTTP/1.1 404 Not Found') {
$url_exists = false;
}
else {
$url_exists = true;
}
if($url_exists){
if(isset($url_headers['Content-Type'])){
$type=strtolower($url_headers['Content-Type']);
$valid_image_type=array();
$valid_image_type['image/png']='';
$valid_image_type['image/jpg']='';
$valid_image_type['image/jpeg']='';
$valid_image_type['image/jpe']='';
$valid_image_type['image/gif']='';
if(isset($valid_image_type[$type])){
return true;
}
else{
return false;
}
}
}
}
if(isImage("http://curiosidadeslegais.org/wp-content/uploads/2016/08/zuera-pa-w5app.jpg")){
echo '<img src="http://curiosidadeslegais.org/wp-content/uploads/2016/08/zuera-pa-w5app.jpg" alt="">';
}
the problem is I don't know why the page is taking so long in the url above. The image no longer exists. and the html prints:
<html>
<head>
<meta name="robots" content="noarchive" />
<meta name="googlebot" content="nosnippet" />
</head>
<body>
<div align=center>
<h3>Error. Page cannot be displayed. Please contact your service provider for more details. (9)</h3>
</div>
</body>
</html>
I don't know why it is taking to long to my function to verify it is not an image and ignores it. any ideas why?
It should be fast to check if image exists or not to print it or not. but in this case it is taking so long.
Upvotes: 0
Views: 80
Reputation: 4253
I add this to limit the time to search for image. I don't know if it is the best way, but...
ini_set('default_socket_timeout', 5);
Upvotes: 0
Reputation: 23958
file_get_contents can return headers and have a max timeout set.
$options = stream_context_create(array('http'=>
array(
"timeout" => 1, // one second
"method" => "GET",
"header" => "Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
));
$url_headers = file_get_contents($url, false, $options);
This is untested since I'm typing on my phone.
Another thing I notice in your code is the $url_exists = true;
why? Why not just move the code below up and replace above line with everything inside the if($url_exists == true)
.
It's not the reason for the slow code but it's completely unnecessary.
Upvotes: 1