5

Here is my code.

$filename = "$myMedia catalog/category/ $myImage.png";
$filename = str_replace(" ", "", $filename);

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}

The variable above outputs http://50.87.6.244/~storeupp/media/catalog/category/Game_Used.png which does exist. However, it says that it does not exists.

Any idea why?

  • possible duplicate of [PHP file\_exists() for URL/robots.txt returns false](http://stackoverflow.com/questions/11966187/php-file-exists-for-url-robots-txt-returns-false) – mario Feb 25 '13 at 18:47
  • Sorry. I did a search but couldn't find what was wrong :( –  Feb 25 '13 at 18:50
  • 2
    Why are you putting spaces in `$filename` if you're just going to remove them on the next line? – Barmar Feb 25 '13 at 19:01
  • Possible duplicate of [PHP: How to check if image file exists?](http://stackoverflow.com/questions/7991425/php-how-to-check-if-image-file-exists) – Cees Timmerman May 19 '17 at 09:02

6 Answers6

5

Just try to use like this:

 $filename = dirname(__FILE__) . "/ $myMedia catalog/category/ $myImage.png";
 $filename = str_replace(" ", "", $filename);

 if (file_exists($filename)) {
     echo "The file $filename exists";
 } else {
     echo "The file $filename does not exist";
 }
Vineet1982
  • 7,730
  • 4
  • 32
  • 67
  • Thanks so much! Yah I just needed to remove the http:// and only include the directory url. Thank you! Will accept in 7 minutes :) +Vote –  Feb 25 '13 at 18:48
4

I don't know, but I think, the following code will be more successful if you have external web items as assets:

$filename = $myMedia."catalog/category/".$myImage.".png";
$headers = @get_headers($filename);
$exists = ($file_headers[0] == 'HTTP/1.1 404 Not Found');
Michael
  • 621
  • 5
  • 17
2

OT: Instead of using spaces and str_replace(" ", "", $filename) you can surround variable betwen "{}" brackets.

$filename = "{$myMedia}catalog/category/{$myImage}.png";

user2410595
  • 369
  • 3
  • 4
0

That file looks like it is outside of your web root. As a result it is not available via the web. If you're trying to check a file that is local on your machine, use the file root instead. (i.e. /path/to/media/catalog/category/Game_Used.png)

John Conde
  • 217,595
  • 99
  • 455
  • 496
0

You need to reference the path to the file or the directory you cannot use http:// links

file_exists documentation

Matt Busche
  • 14,216
  • 5
  • 36
  • 61
0

In the documentation it states that the file_exists() function is only available with some URL wrappers as of PHP 5.0.

christopher
  • 26,815
  • 5
  • 55
  • 89