user1717480
user1717480

Reputation:

PHP if file exists

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?

Upvotes: 6

Views: 30029

Answers (6)

user2410595
user2410595

Reputation: 377

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

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

Upvotes: 2

Michael
Michael

Reputation: 629

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

Upvotes: 4

Vineet1982
Vineet1982

Reputation: 7918

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";
 }

Upvotes: 6

christopher
christopher

Reputation: 27346

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

Upvotes: 0

Matt Busche
Matt Busche

Reputation: 14333

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

file_exists documentation

Upvotes: 0

John Conde
John Conde

Reputation: 219894

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)

Upvotes: 0

Related Questions