Johan
Johan

Reputation: 189

PHP - Failed to open stream: no such file or directory - for existing file

I'm writing a PHP application and in my code i want to create create and return images to the browser. However, sometimes i'm getting some weird results where the image cannot be created since the file does not seem to exist.

Here is a sample error message I get and the code in a nutshell. I do know that the image exists, but still the method sometimes fails, and sometimes it succeeds, even for the same file.

The error:

Warning: imagecreatefrompng(path/to/image.png) [function.imagecreatefrompng]: failed to open stream: No such file or directory in file test.php on line 301

The code:

if (file_exists($filename)) {
    $image = imagecreatefrompng($filename);
}

I would greatly appreciate any hints or tips of what might be wrong and how I can improve the code to be more stabile.

Upvotes: 0

Views: 6570

Answers (6)

jcobhams
jcobhams

Reputation: 824

bro check for white spaces in your filepath. I recently had this issue while i was tring to include a file from a module i was creating for an app. Other modules included well when called but one didnt. It turned out that there was a white space in the filepath. I suggest u try php trim() function. If this works holla.

Upvotes: 0

Conex
Conex

Reputation: 822

You can try GD :

IF($img = @GETIMAGESIZE("testimage.gif")){ 
     ECHO "image exists"; 
}ELSE{ 
     ECHO "image does not exist"; 
} 

Upvotes: 0

Shoe
Shoe

Reputation: 76240

Use is_readable() to check whatever you have permission to access that file.

Upvotes: 0

Ruel
Ruel

Reputation: 15780

I suggest you use is_readable

if (is_readable($filename)) {
    $image = imagecreatefrompng($filename);
}

Upvotes: 1

Ioannis Karadimas
Ioannis Karadimas

Reputation: 7896

Have you considered checking for the correct permissions? If the file cannot be read, but the directory can, you would get file_exists(...) = true, but would not be able to open a handle to the file.

Upvotes: 0

Patrick
Patrick

Reputation: 7712

The file may "exist" but is the file accessible? what does file_exists actually do?

if it opens the file and then closes it make sure that the file is actualy closed and not locked before imagecreatedfrompng fires.

it would be a good idea to try catching the error in a loop and make 4 or 5 attempts before handing back a controlled error.

maybe try is_readable() or is_writable() instead?

Upvotes: 0

Related Questions