开发者

Image file writing: safe way to lock a file

开发者 https://www.devze.com 2023-03-08 08:01 出处:网络
I have a website where people submit content that is then inserted into a collective image. My code works, but I found one issue so far:

I have a website where people submit content that is then inserted into a collective image. My code works, but I found one issue so far:

If 2 people try to write at the same time (both let's say, submitted at the same time), this causes the output file to beco开发者_Go百科me 0KB, another words, it's just an empty file.

I'm writing using an output buffer, GD2 and file_put_contents like so:

ob_start();
imagejpeg($map);
file_put_contents(MAP, ob_get_contents(), FILE_BINARY);
ob_end_clean();

What I'm wondering is what is the best way to go about solving this issue?

Thanks!


file_put_contents(MAP, ob_get_contents(), LOCK_EX)


The documented locking mechanisms in PHP that I tried a while back did not seem to reliably prevent clashes on my system. Even for a simple website counter I ended up using an empty file with the counter value in the actual filename after some other attempts, because file renaming at least is an atomic operation.

The problems probably depend on operating system and file system and might even be fixed these days, but if you do keep having problems like this you could try implementing your own way of locking by renaming the file to something else before modifying it, and then renaming it back after you are done.

Alternatively, you could consider storing the image in a database.

0

精彩评论

暂无评论...
验证码 换一张
取 消