I want to append new rules between two comments in an .htaccess file
Order deny,allow
Deny from All
# COMMENT_OPEN #
allow from 151.106.35.164
allow from 152.106.35.164
# COMMENT_CLOSE #
I want to append the new content between the comments, so it appears as the following:
allow from 151.106.35.164
allow from 152.106.35.164
allow from 153.106.35.164
but only if no duplicate is found.
This is the PHP code I tried:
<?php
$htaccess_content = file_get_contents('/path/to/.htaccess'); //open the .htaccess file
$new_rules = 'allow from 153.106.35.164';
$COMMENT_OPEN = "# COMMENT_OPEN #";
$COMMENT_CLOSE = "# COMMENT_CLOSE #";
$search = "/[^\$COMMENT_OPEN](.*)[^\$COMMENT_CLOSE]/";
$replace = "$COMMENT_OPEN \n$new_rules\n $COMMENT_CLOSE";
$remove = preg_replace($search, $replace, $htaccess_content);
$htaccess_content = preg_replace('/'.preg_quote($remove,'/').'/', $replace, $htaccess_content, 1);
file_put_contents($htaccess, $htaccess_content); //save to the .htaccess file
?>
I need suggestions on how to:
- Get the content between the comments (to manipulate it).
- Replace with the new content between the comments.
Update
Working Solution
//Function to get the content between two strings
function get_string_between($string, $start, $end){
$string = ' ' . $string;
$ini = strpos($string, $start);
if ($ini == 0) return '';
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$htaccess_content = file_get_contents('/path/to/.htaccess'); //open the .htaccess file
$updated_rules = '';
$new_rules = 'allow from 153.106.35.164';
$COMMENT_OPEN = "# COMMENT_OPEN #";
$COMMENT_CLOSE = "# COMMENT_CLOSE #";
$current_rules = get_string_between($htaccess_content, $COMMENT_OPEN, $COMMENT_CLOSE);
//If rule not found
if( strpos( $htaccess_content, $new_rules ) === false ) {
/* Add new rule */
$updated_rules = trim($current_rules) ."\n". $new_rules;
$pattern = '/'.preg_quote($COMMENT_OPEN).'[\s\S]+?'.preg_quote($COMMENT_CLOSE).'/';
$replacement = $COMMENT_OPEN."\n\n".$updated_rules."\n\n".$COMMENT_CLOSE;
$htaccess_content = preg_replace($pattern, $replacement, $htaccess_content);
}
file_put_contents('/path/to/.htaccess', $htaccess_content); //save to the .htaccess file