Reputation: 1472
This spits out a whole heap of NO's but the images are there and path correct as they are displayed by <img>
.
foreach ($imageNames as $imageName)
{
$image = 'http://path/' . $imageName . '.jpg';
if (file_exists($image)) {
echo 'YES';
} else {
echo 'NO';
}
echo '<img src="' . $image . '">';
}
Upvotes: 7
Views: 24102
Reputation: 55
This is what I did. It covers more possible outcomes with getting the headers because if you can't access the file it's not always just "404 Not Found". Sometimes it's "Moved Permanently", "Forbidden", and other possible messages. However it's just " 200 OK" if the file exists, and can be accessed. The part with HTTP can have 1.1, or 1.0 after it, which is why I just used strpos to be more reliable for every situation.
$file_headers = @get_headers( 'http://example.com/image.jpg' );
$is_the_file_accessable = true;
if( strpos( $file_headers[0], ' 200 OK' ) !== false ){
$is_the_file_accessable = false;
}
if( $is_the_file_accessable ){
// THE IMAGE CAN BE ACCESSED.
}
else
{
// THE IMAGE CANNOT BE ACCESSED.
}
Upvotes: 1
Reputation: 113355
file_exists
uses local path, not a URL.
A solution would be this:
$url=getimagesize(your_url);
if(!is_array($url))
{
// The image doesn't exist
}
else
{
// The image exists
}
See this for more information.
Also, looking for the response headers (using the get_headers
function) would be a better alternative. Just check if the response is 404:
if(@get_headers($your_url)[0] == 'HTTP/1.1 404 Not Found')
{
// The image doesn't exist
}
else
{
// The image exists
}
Upvotes: 16
Reputation: 107
function remote_file_exists($file){
$url=getimagesize($file);
if(is_array($url))
{
return true;
}
else {
return false;
}
$file='http://www.site.com/pic.jpg';
echo remote_file_exists($file); // return true if found and if not found it will return false
Upvotes: 0
Reputation: 597
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($retcode==200) echo 'YES';
else echo 'NO';
Upvotes: 2
Reputation: 418
file_exists looks for a local path, not an "http://" URL
use:
$file = 'http://www.domain.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
Upvotes: 15