html - Add lines to file by using array commands with php -
i'm trying make php script adds ip firewall. i'm not entirely sure i'm doing wrong. i'm trying insert $ip
12th line of data on iptables
write iptables2
. there way should doing or easiest?
<?php //firewall string $ip = "-a input -s " . $_server['server_addr'] . " -j accept" . "\n"; //turn file array $file = file('iptables'); //insert string array $res = array_splice($file, 12, 0, $ip); //write file file_put_contents("iptables2", $res); //display new file $iptables2 = file("iptables2"); echo "<ul>"; foreach($iptables2 $s => $r) { echo "<li>" . $s . "=>" . $r . "</li>"; } echo "</ul>"; ?>
iptables
looks this:
*filter -a input -i lo -j accept -a input -m state --state established -j accept -a input -p udp --match multiport --dports 10000:20000 -j accept # port 5060 -a input -s xxx.xxx.xxx.xxx -j accept -a input -s xxx.xxx.xxx.xxx -j accept -a input -s xxx.xxx.xxx.xxx -j accept # remote operators -a input -s xxx.xxx.xxx.xxx -j accept -a input -s xxx.xxx.xxx.xxx -j accept # remote phones -a input -s xxx.xxx.xxx.xxx -j accept -a input -s xxx.xxx.xxx.xxx -j accept -a input -s xxx.xxx.xxx.xxx -j accept # port 3306 - mysql known sources -a input -p tcp -m tcp -s 127.0.0.1 --dport 3306 -j accept # reject rest -a input -p tcp -m tcp -j reject --reject-with tcp-reset -a input -p udp -m udp -j reject commit
line 12 # remote phones
, , want -a input -s xxx.xxx.xxx.xxx -j accept
inserted after line 12.
this can done using regex find , replace # remote operators
. dont have know line string appears.
$iptables= '*filter -a input -i lo -j accept -a input -m state --state established -j accept -a input -p udp --match multiport --dports 10000:20000 -j accept # port 5060 -a input -s xxx.xxx.xxx.xxx -j accept -a input -s xxx.xxx.xxx.xxx -j accept -a input -s xxx.xxx.xxx.xxx -j accept # remote operators -a input -s xxx.xxx.xxx.xxx -j accept -a input -s xxx.xxx.xxx.xxx -j accept # remote phones -a input -s xxx.xxx.xxx.xxx -j accept -a input -s xxx.xxx.xxx.xxx -j accept -a input -s xxx.xxx.xxx.xxx -j accept # port 3306 - mysql known sources -a input -p tcp -m tcp -s 127.0.0.1 --dport 3306 -j accept # reject rest -a input -p tcp -m tcp -j reject --reject-with tcp-reset -a input -p udp -m udp -j reject commit'; $search = '# remote operators'; $ip = '-a input -s yyy.yyy.yyy.yyy -j accept'; echo preg_replace('/^' . $search . '.*/m', "$search\n$ip", $iptables);
you can see live example @ http://sandbox.onlinephpfunctions.com/code/3a0d6dddd228ef79d441b015a58f210d054cf04e
in case read contents of $iptables
file.
Comments
Post a Comment