A known XSS attack is using echo $_SERVER[‘PHP_SELF’] in forms. More about this problem on stack overflow. Anyhow, recently I have been working on a project, where I was to extend existing PHP code, and I noticed this vulnerability to be present in the code. As this is a case of “replace string in all files”, this can be solved with a single command.

However, it sounded much simpler then it was. I must admit I have little experience with regular expressions, or the differences between the regular expressions in perl and sed, as the following expression worked in sed but not in perl. Another problem was escaping, especially in my previous failed attempt that was using -exec as find parameter.(As recommended here) That would need double escaping and such. Way too messy, therefore, xargs looks much cleaner. Anyhow, the following code is working:


$ find directory -name "*.php" -print | xargs sed -i  "s/<?php echo \$_SERVER\['PHP_SELF'\]; ?>/<?php echo htmlspecialchars\(\$_SERVER\['PHP_SELF'\], ENT_QUOTES, 'utf-8'); ?>/g;"