PHP multithreading in the context of secure write files to implement code _php skills

Source: Internet
Author: User
Tags php multithreading rand touch
Copy Code code as follows:

<?php
/**
* @usage: Used to offer safe file write operation in multiple threads context, arbitory file type
* @author: Rocky Zhang
* @time: Nov 11 2009
* @demo [0]: $handler = Mfopen ($file, ' A + ');
* Mfwrite ($handler, $STR);
*/
function Mfopen ($file, $mode = ' w+ ') {
$tempfile = Generatetempfile ('./tempdir ', $file);
Preg_match ('/b/i ', $mode) | | ($mode. = ' B '); ' B ' is recommended
if (Preg_match ('/\w|a/i ', $mode) &&!is_writable ($file)) {
Exit ("{$file} is not writable!");
}
$filemtime = $filemtime 2 = 0;
$tempdir = DirName ($tempfile);
Is_dir ($tempdir) | | mkdir ($tempdir, 0777);
do {//Do-while used to avoid modify in-a long time copy
Clearstatcache ();
$filemtime = Filemtime ($file);
Copy ($file, $tempfile);
$filemtime 2 = filemtime ($file);
while (($filemtime 2-$filemtime)!= 0);
if (! $handler = fopen ($tempfile, $mode)) {
Exit (' Fail on opening tempfile, write authentication are must on temporary dir! ');
}
Return Array (0=> $handler, 1=> $filemtime, 2=> $file, 3=> $tempfile, 4=> $mode);
}

I do the This function should be optimized further
Function Mfwrite (& $handler, $str = ') {
if (strlen ($STR) > 0) {
$num = fwrite ($handler [0], $STR);
Fflush ($handler [0]);
}
Clearstatcache ();
$mtime = Filemtime ($handler [2]);
if ($mtime = = $handler [1]) {//compare between source file and temporary file
if ($num && $num > 0) {//temporary file has been updated, copy to source file
Copy ($handler [3], $handler [2]) | | Exit
$handler [1] = Filemtime ($handler [3]);
Touch ($handler [2], $handler [1], $handler [1]);
}
else {//source file has been modified, load source file to temporary file
Copy ($handler [2], $handler [3]) | | Exit
Touch ($handler [3], $mtime, $mtime);
$handler [1] = $mtime;
}
}

function Generatetempfile ($tempdir = ' tempdir ', $file) {
$rand = MD5 (Microtime ());
Return "{$tempdir}/{$rand}_". $file;
}
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.