Skip to content

Instantly share code, notes, and snippets.

@mkg20001
Created July 4, 2020 05:36
Show Gist options
  • Save mkg20001/ce421daa9863890f74de9dd43da7fe92 to your computer and use it in GitHub Desktop.
Save mkg20001/ce421daa9863890f74de9dd43da7fe92 to your computer and use it in GitHub Desktop.

A snippet that allows securly modifying the .htaccess file

Remeber to replace your-plugin with the id of your plugin

<?php
function patch_htaccess($add = false) {
// first strips our stuff, then adds new stuff if added
$htaccess = ABSPATH . "/.htaccess";
$content = file_get_contents($htaccess);
$byLine = explode("\n", $content);
$out = [];
$ignore = false;
if ($add) {
$out[] = "# BEGIN your-plugin";
foreach ($add as &$addLine) {
$out[] = $addLine;
}
$out[] = "# END your-plugin";
}
foreach ($byLine as &$line) {
if ($ignore) {
preg_match('/^.+END.+your-plugin.*$/i', $line, $matches, PREG_OFFSET_CAPTURE, 0);
if (sizeof($matches)) {
$ignore = false;
}
} else {
preg_match('/^.+BEGIN.+your-plugin.*$/i', $line, $matches, PREG_OFFSET_CAPTURE, 0);
if (sizeof($matches)) {
$ignore = true;
} else {
$out[] = $line;
}
}
}
$new = implode("\n", $out);
file_put_contents($htaccess, $new);
}
function htaccess_enable() {
patch_htaccess(explode("\n", file_get_contents(__DIR__ . "/config.txt")));
}
function htaccess_disable() {
patch_htaccess();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment