April 7, 2013

Append to file…will I need to lock

User1684072’s Questions:

Php newbie here

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. I am using file_put_contents. Here is VERY simplified version of my code:

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

So should I ignore lock or is one needed?? How should I solve this problem

Thanks a lot.

Use fopen() with a switch. 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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!