Question

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!

Was it helpful?

Solution

file_put_contents(MAP, ob_get_contents(), LOCK_EX)

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top