I use insert_with_markers in a couple of my plugins to add some small bits of code to the htaccess file. What I'm unclear about is how to remove the code and markers.

For example, if I call the function like this:-

insert_with_markers($htaccess, "marker","RewriteBase /foobar");

The result in htaccess is:-

# BEGIN marker
RewriteBase /foobar
# END marker

I can use insert_with_markers, with an empty string, like so:-

insert_with_markers($htaccess, "marker","");

Which removes all the code, but the markers remain, like this:-

# BEGIN marker

# END marker

Does anybody know of a clean way to remove the markers as well?... that doesn't involve filtering the htaccess file with regex? I would like to be able to uninstall my plugins and remove all the traces if possible.

up vote 0 down vote accepted

If you know the exact code that is inserted, then read the htaccess file with a function that contains fread command, and do a search for your inserted text, replacing the found text with an empty string. Then fwrite the text to the htaccess file.

If you are just looking for a way to remove the # BEGIN MARKER / # END MARKER text, then use the same process.

I'm not sure if there is a standard way or function to do this, but something like this I think would be a good starting point...

function remove_marker($contents, $marker) {
    $posa = strpos($contents, '# BEGIN '.$marker);
    $posb = strpos($contents, '# END '.$marker) + strlen('# END '.$marker);
    $newcontent = substr($contents, 0, $posa);
    $newcontent .= substr($contents, $posb, strlen($contents));
    return $newcontent;
}

$marker = 'marker';

// rewrite file using WP Filesystem
ob_start(); 
$creds = request_filesystem_credentials('', false, false, dirname($htaccess), null, true);
ob_end_clean();
if ($creds) {
    $filesystem = WP_Filesystem($creds, dirname($htaccess), true);}
    if ($filesystem) {
        global $wp_filesystem;
        $contents = $wp_filesystem->get_contents($htaccess);
        $newcontents = remove_marker($contents, $marker);
        $writeresult = $wp_filesystem->put_contents($htaccess, $newcontents, FS_CHMOD_FILE);
    }
}

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.