6

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?

4
  • possible duplicate of PHP file_exists() for URL/robots.txt returns false Commented Feb 25, 2013 at 18:47
  • Sorry. I did a search but couldn't find what was wrong :( Commented Feb 25, 2013 at 18:50
  • 2
    Why are you putting spaces in $filename if you're just going to remove them on the next line? Commented Feb 25, 2013 at 19:01
  • Possible duplicate of PHP: How to check if image file exists? Commented May 19, 2017 at 9:02

6 Answers 6

6

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";
 }
Sign up to request clarification or add additional context in comments.

1 Comment

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
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');

Comments

2

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

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

Comments

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)

Comments

0

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

file_exists documentation

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.