Edit BIND config file using PHP

Solution:

You can use file_get_content(), update the file content, then push the new data with file_put_content().

What we need is some comments where you need to insert new line :

view "internal"
{

match-clients { localnets; };
match-destinations { localnets; };
recursion yes;

include "/etc/named.root.hints";
    
#INTERNAL
zone "my.internal.zone" {
type master;
file "my.internal.zone.db";
};

};


view "external"
{

match-clients { !localnets; !localhost; };
match-destinations { !localnets; !localhost; };

recursion no;
    
include "/etc/named.root.hints";

#EXTERNAL
zone "my.external.zone" {
type master;
file "my.external.zone.db";
};
};

So you can catch your comments with PHP and add content after :

$confText = file_get_contents('your_file_path') ;

$newExternalZone = PHP_EOL.
'zone "my.new.external.zone" {
type master;
file "my.new.external.zone.db";
};'.PHP_EOL ;

preg_replace("/(#EXTERNAL)/", "$1".$newExternalZone, $confText) ;

file_put_contents('your_file_path', $confText) ;

The code is quite simple here, catch the #External and put $newExternalZone after ! You can update and use data comming from POST,GET or other for newExternalZone.

Answer

Solution:

I was able to do it using the below code. The code accepts arguments using PHP CLI and creates a new file with the values.

$file = file('named.conf');

$arg =  getopt("", array('zone:', 'type:', 'file:'));

$internal_end = 0;
$external_end = 0;
$flag = false;
$count = 0;
foreach ($file as $index => $line) {
    if (preg_match('/view\s*"internal"\s*{/i', $line) !== 1 && !$flag) {
        continue;
    }
    $flag = true;

    $ob =  substr_count($line, '{');
    $count += $ob;
    $cb =  substr_count($line, '}');
    $count -= $cb;
    if ($count == 0) {
        $internal_end = $index;
        break;
    }
}



array_splice($file, $internal_end, 0, array(
    "\n",
    "zone \"".$arg['zone']."\" {\n",
    "\ttype ".$arg['type'].";\n",
    "\tfile \"".$arg['file']."\";\n",
    "};\n",
    "\n"
));

$flag = false;
$count = 0;
foreach ($file as $index => $line) {
    if (preg_match('/view\s*"external"\s*{/i', $line) !== 1 && !$flag) {
        continue;
    }
    $flag = true;

    $ob =  substr_count($line, '{');
    $count += $ob;
    $cb =  substr_count($line, '}');
    $count -= $cb;
    if ($count == 0) {
        $external_end = $index;
        break;
    }
}


array_splice($file, $external_end, 0, array(
    "\n",
    "zone \"".$arg['zone']."\" {\n",
    "\ttype ".$arg['type'].";\n",
    "\tfile \"".$arg['file']."\";\n",
    "};\n",
    "\n"
));


file_put_contents('named_new.conf', implode('', $file));

To execute the code call php script.php --zone=my.new.external.zone --type=master --file=my.new.external.zone.db

Source