开发者

Does this php code secure me from SQL injection and XSS?

I have sanitize class that I run before anything else on every pa开发者_如何学JAVAge of my site. I'm pretty sure addslashes is the same as escaping with mysql_real_escape_string heres the class.

class sanatize
{
private static $singleton;

function __construct(){

    $_CLEAN_POST = array();
    $_CLEAN_GET = array();
    $_CLEAN_REQUEST = array();

    foreach($_REQUEST as $key => $value)
    {
        $key = addslashes(trim(strip_tags($key)));
        $value = addslashes(trim(strip_tags($value)));

        $_CLEAN_REQUEST[$key] = $value;
    }
    foreach($_GET as $key => $value)
    {
        $key = addslashes(trim(strip_tags($key)));
        $value = addslashes(trim(strip_tags($value)));

        $_CLEAN_GET[$key] = $value;
    }
    foreach($_POST as $key => $value)
    {
        if(is_array($value)){
            foreach($value as $key2 => $value2){

                $key2 = addslashes(trim(strip_tags($key2)));
                $value2 = addslashes(trim(strip_tags($value2)));

                $_CLEAN_POST[$key][$key2] = $value2;
            }
        }
        else{
            $key = addslashes(trim(strip_tags($key)));
            $value = addslashes(trim(strip_tags($value)));

            $_CLEAN_POST[$key] = $value;
        }
    }
    $_POST = array();
    $_GET = array();
    $_REQUEST = array();

    $_POST = $_CLEAN_POST;
    $_GET = $_CLEAN_GET;
    $_REQUEST = $_CLEAN_REQUEST;
}
function __destruct()
{
    //echo "cleaned";
}

public static function getInstance()
{
    if(is_null(self::$singleton))
    {
        self::$singleton = new sanatize();
    }
    return self::$singleton;
}
}

and then i'll call it using

$sanatize = sanatize::getInstance();


"I'm pretty sure addslashes is the same as escaping with mysql_real_escape_string heres the class."

First, it's not. mysql_real_escape_string is aware of the connection, and takes that connection's character set into account.

Second, you're basically replicating the failed magic_quotes design. Not all of those fields are going into the database, so you're doing unnecessary work. You also have to be careful never to re-escape something in a "clean" array; double-escaping is a very common problem.

In my opinion, the simplest solution to SQL injection is prepared statements. I recommend using either PDO or mysqli.

EDIT: Since you're already using mysqli, you should forget about this CLEAN idea, and simply use MySQLi_STMT. mysqli::prepare gives an example of how to create and bind variables to a prepared statement. Note the ? place-holder. Also look at mysqli_stmt::bind_param.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜