Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

You could lock the file using flock(). Since PHP 5.3.2 the file remains locked until explicitely unlocked, so you need to make sure that the version of the PHP on the server you're running the code is higher than or at least 5.3.2

There is no way to keep a file open between sereral execution of the same script (luckily:)

Opening a file is not very intensive, I suspect it does not worth setting up a "semi-server" that keep the file open.

Why do you need that ?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top