Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to check if image file exists?

I need to see if a specific image exists on my cdn.

I've tried the following and it doesn't work:

if (file_exists(http://www.example.com/images/$filename)) {     echo "The file exists"; } else {     echo "The file does not exist"; } 

Even if the image exists or doesn't exist, it always says "The file exists". I'm not sure why its not working...

like image 387
PaperChase Avatar asked Nov 03 '11 07:11

PaperChase


People also ask

How do you check if a file is an image in PHP?

Using file extension and getimagesize function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.

How do you check if file is exists in PHP?

The file_exists() function checks whether a file or directory exists.

How do I check if an image is URL?

403, 404, 302 and 301 are the several main HTTP codes to seek when checking that the URL no longer contains what it should do. Using exif_imagetype() as a request method gives the option to also confirm what type of image the content truly is. Then checking for key in the string of the HTTP response header.


2 Answers

You need the filename in quotation marks at least (as string):

if (file_exists('http://www.mydomain.com/images/'.$filename)) {  … } 

Also, make sure $filename is properly validated. And then, it will only work when allow_url_fopen is activated in your PHP config

like image 182
knittl Avatar answered Oct 01 '22 11:10

knittl


if (file_exists('http://www.mydomain.com/images/'.$filename)) {} 

This didn't work for me. The way I did it was using getimagesize.

$src = 'http://www.mydomain.com/images/'.$filename;  if (@getimagesize($src)) { 

Note that the '@' will mean that if the image does not exist (in which case the function would usually throw an error: getimagesize(http://www.mydomain.com/images/filename.png) [function.getimagesize]: failed) it will return false.

like image 38
Jeffrey Jenkinson Avatar answered Oct 01 '22 11:10

Jeffrey Jenkinson