Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file locking in php

Tags:

php

locking

I had a newcomer (the next door teenager) write some php code to track some usage on my web site. I'm not familiar with php so I'm asking a bit about concurrent file access.

My native app (on Windows), occasionally logs some data to my site by hitting the URL that contains my php script. The native app does not examine the returned data.

        $fh = fopen($updateFile, 'a') or die("can't open file");
        fwrite($fh, $ip);
        fwrite($fh, ', ');
        fwrite($fh, $date);
        fwrite($fh, ', ');
        fwrite($fh, implode(', ', $_GET));
        fwrite($fh, "\r\n");
        fclose($fh);

This is a low traffic site, and the data is not critical. But what happens if two users collide and two instances of the script each try to add a line to the file? Is there any implicit file locking in php?

Is the code above at least safe from locking up and never returning control to my user? Can the file get corrupted? If I have the script above delete the file every month, what happens if another instance of the script is in the middle of writing to the file?

like image 359
RobertFrank Avatar asked Mar 27 '11 13:03

RobertFrank


People also ask

What is PHP locking file?

File locking is an important task. It restricts other users from changing a specific file. It allows only one user at a time to access or modify it. PHP provides the flock() method for portable advisory file locking.

What is the purpose of file locking?

File locking is a data management feature that restricts other users from changing a specific file. This allows only one user or process access to this file at any given time. This is to prevent the problem of interceding updates on the same files.

What is the use of flock () function in PHP?

The flock() function allows us to perform a simple reader/writer model that can be used on virtually every platform. The possible locks are LOCK_SH:Shared lock (reader). Allow other processes to access the file, LOCK_EX: Exclusive lock.

What is file locking in Linux?

File locking is a mechanism to restrict access to a file among multiple processes. It allows only one process to access the file in a specific time, thus avoiding the interceding update problem.


1 Answers

You should put a lock on the file:

<?php
$fp = fopen($updateFile, 'w+');
if(flock($fp, LOCK_EX)) {
fwrite($fp, 'a');
flock($fp, LOCK_UN);
} else {
echo 'can\'t lock';
}

fclose($fp);
like image 184
Rho Avatar answered Oct 30 '22 03:10

Rho