user2062541
user2062541

Reputation: 51

imagejpeg() unable to open for writing - sometimes it works, sometimes not

I try to save an image resource to an image by the following code:

imagejpeg ($destination_res, $destination, 100);

The script also contains a file-upload which does work (the files always exist in the destination folder) - after this file upload I want to use this file for imagejpeg(). The problem is that sometimes my code does work, sometimes not. In case of not working I get the following error by PHP:

Warning: imagejpeg(): Unable to open [path] for writing: Invalid argument in script on line xy

I guess that there is a problem with the copying process - maybe the copying process after the file upload is not completely finished and therefore it is not writeable.

But I also tried to check if file_exists($destination) and if file is_writable($destination) before the imagejpeg() command. Both checks return TRUE even in case of the warning error.

If I put a sleep(2) between file upload and imagejpeg() fewer errors happen. The longer the sleep lasts, the fewer errors occur.

Can anyone help me?

I'm working on my PC with OS Windows 8 - I use IIS 8 and PHP 5.3.3.

Upvotes: 4

Views: 3535

Answers (1)

powtac
powtac

Reputation: 41050

PHP has an internal cache for used path, when you create files, it could be that the cache gets outdated and PHP throws error, even if files are there (some miliseconds later)...

To avoid problems with created files which can not be found in realtime use clearstatcache(). It resets the internal PHP cache for paths.

Call clearstatcache() after you create files, and before you access created files.

clearstatcache();
imagejpeg ($destination_res, $destination, 100);

Upvotes: 2

Related Questions