PHP: List of common pitfalls

I have seen a lot of PHP code, good and bad ones. Even some exploits for pretty common things that were just careless implemented.
In this post i want to share some of these pitfalls so you dont have to make them on your own.

$_GET Vulerabilities

str_replace() validation


The str_replace() validation is still vulnerable against a directory change attack.
Simple hack would be:
str_replace() does not double replace. If you want to do so use code like this:

while(strpos($_GET['file'], '../') !== FALSE) {
  $_GET['file'] = str_replace('../','',$_GET['file']);
// Or
$_GET['file'] = preg_replace('\.+/+', '', $_GET['file']);

Another example for wrong str_replace() usage:


It is the same problem like above and easily hackable:

Suffix/Prefix validation


Adding a prefix and a suffix is good, but still vulnerable.
Possible hack:
The "%00" is a nullbyte, so the internal representation of a zero. Everything behind the nullbyte will be ignored.
The the real command will look like this:
On many systems this will include the /etc/passwd!

SQL validation

mysql_query('SELECT * FROM articles WHERE id = '.$_GET['id'].' ;');

This is very dangerous! The $_GET value can be changed in the query and can give controll over the SQL query!
A simple fix could look like this:

mysql_query('SELECT * FROM articles WHERE id = '.(int)$_GET['id'].' ;');

Still not perfect but secure.


You have some more examples?
Let me know them! Thanks.

No related posts.


Die Kommentarfunktion zu diesem Beitrag wurde deaktiviert.