Since PHP is convenient tool to process text contents and data from internet, sometimes we use PHP to process a large amount of data as batch script program, and running for a long time. But we may want to change the process rules from PHP script without restarting the program manually. In this case a self modification detection is very useful.
Example Usage
Another way to deal updating
Finally, there is another problem: After terminated, how would make PHP restart automatically?
I suggest a solution by using DOS batch file, running a endless loop like this:
class ScriptUpdater{
private static $scripts;
private static $md5;
//add a script file to watch the modification, filePath can be string or array
public static function addScript($filePath){
if(is_array($filePath)) return self::addScript(array_pop($filePath)) && self::addScript($filePath);
return ($md5 = @md5_file($filePath)) && (self::$scripts[$filePath] = $md5);
}
//reutrn the modified file or false, (if modified excutes a function)
public static function update($onUpdateFunc = null, $args = null){
if($onUpdateFunc) return self::_watch() && @call_user_func_array($onUpdateFunc, $args);
else return self::_watch();
}
//reutrn the modified file or false
private static function _watch(){
foreach(self::$scripts as $file => $md5)
if(@md5_file($file) != $md5) return $file;
return false;
}
}
Example Usage
//put this part at the beginning of main program
ScriptUpdater::addScript(array(
__FILE__, //watch the current main program
get_included_files(), //and all required files
));
//while(...){
//Put this part when necessary, usually in the beginning of a loop
if($file = ScriptUpdater::update()){
echo " -- $file modified, exiting...\n";
exit();
}
//...
//Process something here
// } end of loop
Another way to deal updating
//calling the die function
ScriptUpdater::update('die', array('PHP file has been modified, run this program again.'));
Finally, there is another problem: After terminated, how would make PHP restart automatically?
I suggest a solution by using DOS batch file, running a endless loop like this:
@echo off chcp 65001 cls IF NOT EXIST MyProgram.php GOTO Skip echo Starting MyProgram at %TIME% for /l %%i in (1 1 10000) DO ( php MyProgram.php echo MyProgram stopped ) pause :Skip echo MyProgram.php is not exists pause
留言