图像文件写入:锁定文件的安全方法

发布于 2024-11-09 16:07:24 字数 341 浏览 3 评论 0 原文

我有一个网站,人们可以提交内容,然后将其插入到集体图像中。我的代码可以工作,但到目前为止我发现一个问题:

如果两个人尝试同时写入(比如说,同时提交),这会导致输出文件变成 0KB,换句话说,它只是一个空文件文件。

我正在使用输出缓冲区、GD2 和 file_put_contents 进行编写,如下所示:

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

我想知道解决此问题的最佳方法是什么?

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青巷忧颜 2024-11-16 16:07:24

file_put_contents(MAP, ob_get_contents(), LOCK_EX)

file_put_contents(MAP, ob_get_contents(), LOCK_EX)

↙厌世 2024-11-16 16:07:24

我不久前尝试过的 PHP 中记录的锁定机制似乎并不能可靠地防止我的系统发生冲突。即使对于一个简单的网站计数器,经过一些其他尝试后,我最终还是使用了一个空文件,其中计数器值在实际文件名中,因为文件重命名至少是一个原子操作。

这些问题可能取决于操作系统和文件系统,甚至可能已经得到解决,但如果您确实继续遇到这样的问题,您可以尝试通过在修改文件之前将文件重命名为其他内容,然后重命名来实现自己的锁定方式完成后将其返回。

或者,您可以考虑将图像存储在数据库中。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文