Home >Backend Development >PHP Tutorial >php file lock write

php file lock write

巴扎黑
巴扎黑Original
2016-11-21 11:54:561466browse

PHP file writing method, coping with multi-threaded writing:

Php code

function file_write($file_name, $text, $mode='a', $timeout=30){  
    $handle = fopen($file_name, $mode);  
    while($timeout>0){  
        if ( flock($handle, LOCK_EX) ) {  
            $timeout--;  
            sleep(1);  
        }  
    }  
    if ( $timeout > 0 ){  
        fwrite($handle, $text.'\n');  
        flock($handle, LOCK_UN);  
        fclose($handle);  
        return true;  
    }  
    return false;  
}

The handle operated by flock(int $handle, int $operation) function must be an open file pointer.

operation can be one of the following values:

To obtain a shared lock (reading program), set operation to LOCK_SH (set to 1 in versions prior to PHP 4.0.1).

To obtain an exclusive lock (writing program), set operation to LOCK_EX (set to 2 in versions prior to PHP 4.0.1).

To release a lock (whether shared or exclusive), set operation to LOCK_UN (set to 3 in versions prior to PHP 4.0.1).

If you don’t want flock() to block when locked, add LOCK_NB to operation (set to 4 in versions before PHP 4.0.1).


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Learn PHP statementsNext article:Learn PHP statements