How to check if file with deleted image exists in php?

It splashes out a whole bunch of NO, but the images are there and the right way, since they are displayed on <img>.

foreach ($imageNames as $imageName) 
{
    $image = 'http://path/' . $imageName . '.jpg';
    if (file_exists($image)) {
        echo  'YES';
    } else {
        echo 'NO';
    }
    echo '<img src="' . $image . '">';
}
+5
source share
5 answers

file_exists uses a local path, not a URL.

The solution would be:

$url=getimagesize(your_url);

if(!is_array($url))
{
     // The image doesn't exist
}
else
{
     // The image exists
}

See this for more information .

Also, searching for response headers (using a function get_headers) will be a better alternative. Just check if answer 404 matches:

if(@get_headers($your_url)[0] == 'HTTP/1.1 404 Not Found')
{
     // The image doesn't exist
}
else
{
     // The image exists
}
+13
source

file_exists is looking for a local path, not the url "http: //"

using:

$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;
}
+13
source
$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';
+2

This is what I did. It covers more possible results with getting headers, because if you cannot access the file, it is not always just “404 Not Found”. Sometimes these are "Moved Permanentently", "Forbidden" and other possible messages. However, it is simply “200 OK” if the file exists and can be accessed. The HTTP part may have 1.1 or 1.0 after it, so 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.
}
+1
source
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
0
source

All Articles