check if file exists in php

PhpFile Exists

Php Problem Overview


if (!(file_exists(http://mysite.com/images/thumbnail_1286954822.jpg))) {   
$filefound = '0';   					  
}

why won't this work?

Php Solutions


Solution 1 - Php

if (!file_exists('http://example.com/images/thumbnail_1286954822.jpg')) {   
$filefound = '0';
}

Solution 2 - Php

  1. The function expects a string.

  2. file_exists() does not work properly with HTTP URLs.

Solution 3 - Php

file_exists checks whether a file exist in the specified path or not.

Syntax:

file_exists ( string $filename )

Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.

$filename = BASE_DIR."images/a/test.jpg";
if (file_exists($filename)){
	echo "File exist.";
}else{
	echo "File does not exist.";
}

Another alternative method you can use getimagesize(), it will return 0(zero) if file/directory is not available in the specified path.

if (@getimagesize($filename)) {...}

Solution 4 - Php

Based on your comment to Haim, is this a file on your own server? If so, you need to use the file system path, not url (e.g. file_exists( '/path/to/images/thumbnail.jpg' )).

Solution 5 - Php

You can also use PHP get_headers() function.

Example:

function check_file_exists_here($url){
   $result=get_headers($url);
   return stripos($result[0],"200 OK")?true:false; //check if $result[0] has 200 OK
}

if(check_file_exists_here("http://www.mywebsite.com/file.pdf"))
   echo "This file exists";
else
   echo "This file does not exist";

Solution 6 - Php

for me also the file_exists() function is not working properly. So I got this alternative solution. Hope this one help someone

$path = 'http://localhost/admin/public/upload/video_thumbnail/thumbnail_1564385519_0.png';

    if (@GetImageSize($path)) {
        echo 'File exits';
    } else {
        echo "File doesn't exits";
    }

Solution 7 - Php

Check code below

if ($user->image) {
        $filename = "images/" . $user->image;
        if (file_exists($filename)) {
            echo '<br />';
            echo "File exist.";
        } else {
            echo '<br />';
            echo "File does not exist.";
        }
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionanonymousView Question on Stackoverflow
Solution 1 - PhpHaim EvgiView Answer on Stackoverflow
Solution 2 - PhpIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 3 - PhpIRSHADView Answer on Stackoverflow
Solution 4 - PhpJJJView Answer on Stackoverflow
Solution 5 - PhpPradeep KumarView Answer on Stackoverflow
Solution 6 - PhpNashirView Answer on Stackoverflow
Solution 7 - Phpahmad saadView Answer on Stackoverflow