What steps can be taken to identify and remove malicious code injected into .htaccess files on a web server?

Malicious code injected into .htaccess files on a web server can be identified and removed by regularly monitoring the files for any unauthorized changes, scanning the files for suspicious code patterns, and implementing strict file permissions to prevent unauthorized access. Additionally, using security plugins or tools to scan and clean the files can help in detecting and removing any malicious code.

<?php
$htaccess_file = '/path/to/.htaccess';

// Read the contents of the .htaccess file
$htaccess_contents = file_get_contents($htaccess_file);

// Check for any suspicious code patterns
if (preg_match('/eval\((base64_decode|gzinflate|\$_|\$\(.*\))/', $htaccess_contents)) {
    // Remove the suspicious code
    $clean_htaccess_contents = preg_replace('/eval\((base64_decode|gzinflate|\$_|\$\(.*\))/', '', $htaccess_contents);

    // Write the cleaned contents back to the .htaccess file
    file_put_contents($htaccess_file, $clean_htaccess_contents);

    echo 'Malicious code removed from .htaccess file.';
} else {
    echo 'No malicious code found in .htaccess file.';
}
?>