- 论坛徽章:
- 0
|
刚才发文件锁定心得时有网友说用 rename(), 以下是小弟以前的测试程序,顺便贴上来,请指教.
- <?php
- /* ---------------------------------------------------- */
- /* f_lock.php(安全文件操作机制) */
- /* ---------------------------------------------------- */
- /* Target: 摒弃系统提供的 flock, 自己写 f_open */
- /* Author: hightman.bbs@bbs.hightman.net */
- /* Create: 2002/09/29 */
- /* Update: // */
- /* Syntax: $fd = f_open($fpath, MODE); f_close($fd) */
- /* ---------------------------------------------------- */
- // $Id: $
- require ("my_timer.php");
- $time = my_timer::start();
- define("_LOCKED_EXT_", ".LOCK");// .LOCK 作后缀
- define("_WAIT_TIMES_",100);// 20 是 1 秒, 最多等 5秒
- global $LOCKED_FD;
- $OPENED_FD = Array();// fd <=>; fpath
- $OP_CWD = getcwd();
- function clear_locked($errno = 0, $error = \'\') {
- global $OPENED_FD, $OP_CWD;
- chdir($OP_CWD);
- foreach($OPENED_FD as $tmp)
- rename($tmp . _LOCKED_EXT_, $tmp);
- $OPENED_FD = Array();
- if ($errno) {
- echo "<p>;<b>;Error(" . $errno . "): </b>;" . $error . "</p>;\\n";
- }
- }
- function f_lock($fpath) {
- if (empty($fpath)) return;
- $fpath2 = $fpath . _LOCKED_EXT_;
- $i = 0;
- while (file_exists($fpath2)) {
- $i++;
- usleep(50000);
- if ($i == _WAIT_TIMES_) return -1;
- }
- return rename($fpath, $fpath2);
- }
- function f_unlock($fd) {
- global $OPENED_FD;
- if (!is_resource($fd)) return;
- $fpath = $OPENED_FD[$fd];
- rename($fpath . _LOCKED_EXT_, $fpath);
- unset($OPENED_FD[$fd]);
- }
- function f_open($fpath, $mode) {
- global $OPENED_FD;
- f_lock($fpath);
- $fd = fopen($fpath . _LOCKED_EXT_, $mode);
- $OPENED_FD[$fd] = $fpath;
- return ($fd);
- }
- function f_close($fd) {
- fclose($fd);
- f_unlock($fd);
- }
- /////////////////////////////////////////////////////////////////////////
- error_reporting(E_ALL ^ E_NOTICE);
- register_shutdown_function("clear_locked");
- if (set_error_handler("clear_locked")) {
- exit("<B>;ERROR: </B>; <SMALL>;Don\'t use function: set_error_handler() Before using f_open/close() plz ...</SMALL>;");
- }
- $fd = f_open("./1.txt", "r");
- echo fread($fd, 128);
- f_close($fd);
- $time->;over();
- ?>;
复制代码
//附: my_timer.php
- <?php
- class my_timer {
- var $time_start = 0;
- function get_mtime(){
- list($usec, $sec) = explode(' ', microtime(), 2);
- return ((float)$usec + (float)$sec);
- }
- function &start() {
- if (!is_object($this)) {
- $obj = new my_timer;
- $obj->;start();
- return ($obj);
- }
- $this->;time_start = $this->;get_mtime();
- }
- function over() {
- $time = $this->;get_mtime() - $this->;time_start;
- echo \"<p align=\"center\">;<small>;Processed time: $time secs.</small>;</p>;n\";
- }
- }
- ?>;
复制代码 |
|