I was studying on how to include config.php efficiently in ever webpage of a website and I’ve found a great answer here on stackoverlow.
The user “user187291” gave a very interesting answer on how to include it, recommending an “inside out” approach.
$page = isset($_GET['page'])
? preg_replace("/\W+/", "", $_GET['page'])
: "home";
include "$page.php";
The question is, why does he uses preg_replace?
preg_replaceis being used to strip non alphanumeric characters from thepagevariable.This is a very thin attempt at security. The code is attempting to prevent an injection attack.
Consider if the user requested the page http://www.example.com/index.php?page=/etc/passwd
Without sanitizing the input, the password file for the domain would happily be dumped to the screen.
The pattern
\W+removes invalid characters such as the ‘/’ character, preventing simple attacks such as this.