문제

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 become 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top