Imagejpeg () cannot be opened for writing - sometimes it works, sometimes not

I am trying to save an image resource for an image with the following code:

imagejpeg ($destination_res, $destination, 100); 

The script also contains a download file that works (files always exist in the destination folder) - after downloading this file I want to use this file for imagejpeg() . The problem is that sometimes my code really works, sometimes not. In case of inoperability, I get the following PHP error:

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

I think that there is a problem with the copy process - perhaps the copy process after the file download is not completely finished, and therefore it cannot be recorded.

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

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

Can anybody help me?

I work on my PC with Windows 8 - I use IIS 8 and PHP 5.3.3 .

+4
source share
1 answer

PHP has an internal cache for the path used when you create files, it may be that the cache is out of date, and PHP throws an error even if there are files (after a few seconds) ...

To avoid problems with generated files that cannot be found in real time, use clearstatcache() . It flushes the internal PHP cache for paths.

Call clearstatcache() after creating the files and before accessing the created files.

 clearstatcache(); imagejpeg ($destination_res, $destination, 100); 
+2
source

All Articles