Best way to set Lock on PHP File
Hello,
Does anyone know the best way to lock a PHP file after it has been executed. I created a script which is called setup.php which will execute and once it has been executed cannot run again until an unless we remove the lock set on that file,So can anyone suggest me the Best possible way to set Lock on PHP file.
Thanks for your valuable support.
Re: Best way to set Lock on PHP File
One simple way would be to deny access to "install.txt" via htaccess or another access manager, then you can just toggle the file extension from php to txt and vice-versa.
Re: Best way to set Lock on PHP File
You can lock a file use flock() function. This function allows you to performance a simple reader/write model. Once a file is locked with flock(), other processing attempting to write to file have to wait until unlock. It avoid multiprocess at a file that can corrupt it.
Code:
<?php
2 $f = "test2.txt";
3
4 $fo = fopen($f, "wb+") or die("cannot open");
5
6 if(flock($fo, LOCK_EX)){
7 fwrite($fo,"test add a 2 string") or die("cannot write to file");
8 flock($fo, LOCK_UN);
9 }else{
10 die("Cannot lock file");
11 }
12
13 fclose($fo);
14 echo "sucess";
15 ?>