Ok, ok .. donc maintenant je panique.PHP accès aux fichiers simultanés
index1.php
<?
function write_file($filepath,$filecontent) {
$openedfile = fopen($filepath,"w+"); //replace with $openedfile = fopen($filepath,"a"); just in case
flock($openedfile, LOCK_EX);
//add here fclose($openedfile); to work
//add here $openedfile = fopen($filepath,"w+"); to work
fwrite($openedfile,$filecontent);
flock($openedfile, LOCK_UN);
fclose($openedfile);
}
function read_file($filepath) {
$openedfile = fopen($filepath,"r+");
flock($openedfile, LOCK_SH);
sleep(10);
$filecontent = file_get_contents($filepath);
flock($openedfile, LOCK_UN);
fclose($openedfile);
return $filecontent;
}
write_file("Readme.txt","test 1");
$f1 = read_file("Readme.txt");
echo $f1;
?>
index2.php
<?
function write_file($filepath,$filecontent) {
$openedfile = fopen($filepath,"w+"); //replace with $openedfile = fopen($filepath,"a"); to work
flock($openedfile, LOCK_EX);
//add here fclose($openedfile); to work
//add here $openedfile = fopen($filepath,"w+"); to work
fwrite($openedfile,$filecontent);
flock($openedfile, LOCK_UN);
fclose($openedfile);
}
function read_file($filepath) {
$openedfile = fopen($filepath,"r+");
flock($openedfile, LOCK_SH);
$filecontent = file_get_contents($filepath);
flock($openedfile, LOCK_UN);
fclose($openedfile);
return $filecontent;
}
write_file("Readme.txt","test 2");
$f1 = read_file("Readme.txt");
echo $f1;
?>
je lance index1.php, puis après 2 secondes je lance index2.php. Index2.php attend index1.php comme prévu mais index1.php ne montre rien après 10 sec, tandis que index2.php affiche "test 2". Que se passe-t-il?
EDIT: Je l'ai compris: D. J'ai changé
$openedfile = fopen($filepath,"w+");
à
$openedfile = fopen($filepath,"a");
deuxième php et il ne nettoie pas readme.txt lors de l'exécution index2.php plus.
On dirait que vous relâchez le verrou avant l'écriture du fichier. Voir aussi ['fflush'] (http://de.php.net/fflush). – hakre