Search code examples
phpfile-iofopenflat-filedatabase-server

How to keep a file open in PHP?


Possible Duplicate:
File resource persistence in PHP

If using fopen for opening a file, it will be closed and unset at the end of the PHP script even without fclose.

$fp = fopen('data.txt', 'w');
fwrite($fp, 'text');
fclose($fp);

Now if it is a frequently used script, we need to open/close the file with the filesystem too many times (file I/O). It would be better to keep the file open. This is the technique that database systems use.

Is there a function in PHP to leave a file open and do not re-open it on the next run?

Or How we can setup a semi-server to keep a file opened for frequent access by PHP?


Solution

  • No - you cant. You can open the file in the start of your script/scripts and close it in the end. You can operate with the between the opening and the closing as much as you like. For example you can open the file in the header of your site, and close it at the footer.

    To solve the task you require, you might want to take a look at a PHP extension called memcahced. It will store some pieces of information in the RAM of the machine, so that you can reuse them later. You can also add expiration time of each piece of information.

    Take a look at this module here: http://www.php.net/manual/en/book.memcached.php