I have a cron script that compresses images. It basically iterates over folders and then compresses the files in the folder. My problem is that some images are getting processed halfway. My theory is that users are uploading a image, and before the image has finished uploading the file, the compressor tries to compress the file. Thus compressing a half-uploaded image, and resulting in half an image being displayed.
PHP doesn't trigger your action until the files are fully uploaded, but it is possible for your cron
job to start interacting with files before they're fully saved.
When saving something from $_FILES
, save it to a version with a .
prefix on it to tag it as incomplete. Make sure your cron
job skips any such files.
Then, once the save operation is complete, rename the file without the .
prefix to make it eligible for processing.
There are two ways to handle the scenario
Flags
Set flag that files before modify/write it. Our App handles lots of files, we set flags before taking them to process once it's done we remove the flag, as it runs on cron flag is the best way to process files.
Usually, you can an extra column on the table on each file. or you can have an array where you can store all currently handling files.
filemtime()
As you mentioned you can check like if file mtime
is more than 10 min that current time, then you compress them but if some other processes are using the file opened the at the same time. it causes the problem again.
So its better to go with flag. If other processes never modify the files often.