views:

58

answers:

3

I have the following constructor:

public function __construct(){
    foreach($_GET as $key=>$value){
        $_GET[$key] = addslashes($value);
    }
    $this->get = $_GET;
}

and it's used like so:

$app->get['id']

Where 'id' is the parameter being passed through the URL.
Is there a good way to sanitize all the data through the constructor?

A: 

Why are you doing this? To prevent SQL injection?

Preventing injection should be done at the query-building level, and should most definitely be done with a more relevant function like mysql_real_escape_string, which will catch all odd cases, not just quotes. What you are doing here is no better than the infamous magic quotes functionality that has since been removed from PHP.

Matchu
A: 

This will remove unwanted HTML and trim the value by default:

public function __construct($striptags = true, $trim = true){
    foreach($_GET as $key=>$value){
        if ($striptags)
        {
            $_GET[$key] = strip_tags($value);
        }
        if ($trim)
        {
            $_GET[$key] = trim($value);
        }
    }
    $this->get = $_GET;
}

To prevent the default actions just pass false to the constructor as necessary.

FYI, addslahes() really doesn't need to be used any more. If you're concerned with escaping DB data use mysql_real_escape_string() or its DB specific equivelant.

John Conde
+1  A: 

A slightly shorter way to do this:

public function __construct(){
    $this->get = array_map('mysql_real_escape_string', $_GET);
}
code_burgar
That's pretty neat!
kylex