简体   繁体   English

附加到文件...我需要锁定

[英]Append to file…will I need to lock

Php newbie here php新手在这里

I am creating a webpage that stores some information in a text file by appending to it. 我正在创建一个网页,该网页通过附加在文本文件中存储一些信息。 Everytime the webpage loads, there is a small php script that adds information to the end of the text file. 每次加载网页时,都会有一个小的php脚本,它将信息添加到文本文件的末尾。 I am using file_put_contents. 我正在使用file_put_contents。 Here is VERY simplified version of my code: 这是我的代码的非常简化的版本:

<?php
$file = "records.txt";
$current = file_get_contents($file);
$current .= "id = ". $_GET["id"]." \n";
file_put_contents($file, $current );
?>

Here is my concern...if hundreds of people open my webpage, will my script be able to capture ALL the user information without missing anyone. 这是我的关注...如果数百人打开我的网页,我的脚本将能够捕获所有用户信息而不会丢失任何人。 This is extremely important. 这是非常重要的。

I am afraid to lock it(use LOCK_EX) because that would mean that when a new user opens up the webpage the script would not be able to open up and append to the text file if another user is writing to it and thus I would not be able to capture his information which is a BIG problem. 恐怕要锁定它(使用LOCK_EX),因为这意味着当一个新用户打开网页时,如果另一个用户正在写该脚本,该脚本将无法打开并追加到文本文件,因此我不会能够捕获他的信息,这是一个很大的问题。

So should I ignore lock or is one needed?? 那么我应该忽略锁还是需要一个? How should I solve this problem 我应该如何解决这个问题

Thanks a lot. 非常感谢。

Use fopen() with a switch. fopen()与开关一起a This will handle all the problems. 这样可以解决所有问题。

$handle = fopen("somefile.txt", "a");

For your requirements you should not lock the file, but this will probably expose the file to vulnerabilities. 根据您的要求,您不应锁定文件,但这可能会将文件暴露给漏洞。 So I will suggest an alternative instead. 因此,我将建议替代方法。

Instead of a file, insert the information you want on the database . 而不是一个文件,插入你想要的数据库中的信息。

It is not a database but it is similar to locking. 它不是数据库,但类似于锁定。 You can use a queue to store the messages you want to write to the file. 您可以使用队列存储要写入文件的消息。 It can become incredibly large though. 但是它可能变得非常大。

Using a database will be very slow. 使用数据库将非常慢。 Your problem sounds exactly like what log files do, they do it efficiently, are very well tested and are reliable. 您的问题听起来与日志文件的功能完全一样,它们可以高效地进行操作,经过良好的测试并且可靠。 Some of them even support sets of files with a file size of your choosing. 其中一些甚至支持具有您选择的文件大小的文件集。 In theory you would just replace the error message with your data. 从理论上讲,您只需将错误消息替换为数据即可。 Although I have not yet used it myself, I see references to log4j all over the place, so it's a good place to start. 尽管我自己还没有使用过它,但是到处都可以看到对log4j的引用,因此这是一个不错的起点。 It uses Java. 它使用Java。 Java itself has a little logging system built into it that I have used with good results on a small job. Java本身内置了一个小的日志记录系统,我在完成一项小工作时就使用了它,并取得了良好的效果。 You might even be able to treat log4j like a black box and use it for projects built with other languages. 您甚至可以将log4j像黑盒子一样对待,并将其用于使用其他语言构建的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM