主从数据库的IP地址更换时,用到的自动替换功能

主从数据库的IP地址更换时,用到的自动替换功能
这也是工作中遇到的,自己想办法做的自动替换功能,节约很多的时间,办公中能自动的东西就尽量去自动化,节约时间,提高效率。

<?php 
/*
 * 在文件配置中大多数的数据库链接定义的格式是define("TEST_MASTER_DB_HOST", "192.168.1.1"); 现在要替换成define("TEST_MASTER_DB_HOST", "192.168.1.10");
 * 该PHP代码就是用来自动替换Ip地址
 */
$dbNameArr      =    array("testDb",'newDb');
$prefixArr[]    =    array('_MASTER_','_SLAVE_');
$dirPath        =    'D:/wamp/www/test/';
$pathArr        =    array();
$replaceArr     =    array();
// replace start ====================================================================
foreach ($prefixArr[0] as $v)
{
    foreach ($dbNameArr as $val)
    {
        $dbNameUp        =    strtoupper($val);
        $val1            =    'define("'.$dbNameUp.$v.'DB_HOST", "192.168.65.1");';
        $val2            =    'define("'.$dbNameUp.$v.'DB_HOST", "192.168.65.2");';
        $val3            =    'define("'.$dbNameUp.$v.'DB_HOST", "192.168.85.3");';
        $replaceArr[]    =    array($val1,$val3);
        $replaceArr[]    =    array($val2,$val3);
    }
}
foreach ($prefixArr[1] as $v)
{
    foreach ($dbNameArr as $val)
    {
        $dbNameUp        =    strtoupper($val);
        $val1            =    'define("'.$dbNameUp.$v.'DB_HOST", "192.168.65.10");';
        $val2            =    'define("'.$dbNameUp.$v.'DB_HOST", "192.168.65.20");';
        $val3            =    'define("'.$dbNameUp.$v.'DB_HOST", "192.168.85.30");';
        $replaceArr[]    =    array($val1,$val3);
        $replaceArr[]    =    array($val2,$val3);
    }
}
$pathArr    =    file_list($dirPath);
//print_r($pathArr);exit;
 
foreach ($pathArr as $filePath)
{
    replace($filePath,$replaceArr);
}
// replace end ====================================================================
 
function replace($filePath,$replaceArr)
{
    $oldData    =    file_get_contents($filePath);
    foreach ($replaceArr as $v)
    {
        $oldData    =    str_replace($v[0],$v[1],$oldData);
    }
    file_put_contents($filePath,$oldData);
}
function file_list($path)
{
    global $pathArr;
    if ($handle = opendir($path))
    {
        while (false !== ($file = readdir($handle)))
        {
            if ($file != "." && $file != "..")
            {
                //echo $path.": ".$file."<br>";
                if (is_dir($path."/".$file))
                {
                    file_list($path."/".$file);
                }
                else
                {
                    $pathArr[]    = $path."/".$file;
                }
            }
        }
    }
    return $pathArr;
}
?>

Related posts:

One thought on “主从数据库的IP地址更换时,用到的自动替换功能”

Leave a Reply

Your email address will not be published.