Use PHP Regex Replace Line-by-Line to remove Malware from large Database Dumps

When it comes to cleaning huge websites of malware, if the database is several GB in size, it becomes difficult to navigate and remove bad code. PHPMyAdmin and text editors become completely useless for databases over 2GB in size.

Here’s a script I came across recently and turned to be quite helpful in removing malware from database.

<?php

ini_set( 'pcre.backtrack_limit', '50000000000' );
ini_set( 'pcre.recursion_limit', '50000000000' );

$inputfile = fopen( 'inputfile.sql', 'r' ); // replace this before running
$outputfile = fopen( 'outputfile.sql', 'w' ); // replace this before running
$regex = '/myregex/s';
$lines = 0;

if ( $inputfile ) {
  while ( ( $buffer = fgets( $inputfile ) ) !== false ) {
    $lines ++;
    echo 'Line:' . $lines . PHP_EOL;
    $c = preg_replace( $regex, '', $buffer, -1, $count );
    fwrite( $outputfile, $c );
  }
  if ( ! feof( $inputfile ) ) {
    echo "Error: unexpected fgets() fail\n";
  }
  fclose( $inputfile );
  fclose( $outputfile );
  echo "Done!\n";
} else {
  echo "Input issue!\n";
}

Another good method for cleaning malware from the database is using Regex with WP CLI to Search & Replace in Database.

Was this post helpful?

Leave a Reply