Replace the first line of hacked php scripts

If you’ve ever dealt with web servers that have sites running wordpress, you’ve probably dealt with hacked php scripts since pretty much any server running wordpress is going to have a hacked copy of wordpress at some point.  One of the most common things script kiddies do after finding a vulnerable copy of wordpress is to insert backdoor code on the first line; something that looks like this:

<?php if(!isset($GLOBALS["\x61\156\x75\156\x61"])) { $ua=strtolower($_SERVER["\x48\124\x54\120\x5f\125\

As long as you can find a unique pattern that you know would not occur in any legit place in the file, it’s easy to replace the first line using a command line perl script:

find . -type f -name \*.php -exec grep -rl 'isset($GLOBALS' {} \; |xargs -i -n 1 perl -pi -e "s/^.+isset\(\$GLOBALS.*$/\<\?php/g" {}

In this case, I knew the website in question had no legit use of ‘isset($GLOBALS’ in any of the uncompromised php code, so that was the pattern I searched for.  The matching files are piped to xargs to execute a command against each file, and the command is a perl pattern replacement where it replaces the entire first line of the file with <?php to put them back to how they were.

One Reply to “Replace the first line of hacked php scripts”

  1. Pierre-Philippe Lessard

    Your command was not a success for me (find: `grep’ terminated by signal 13).

    Instead, I created a small bash script :


    filelist=$(find . -name \*.php)

    for x in $filelist
    sed -i '/isset($GLOBALS/c\<?php' $x


Leave a Reply

Your email address will not be published. Required fields are marked *