简体   繁体   中英

Is my PDO INSERT INTO enough secure?

I would like your opinion about my code. Is it secure enough against any injections. Thanks for your replies.

class Product extends DB {

  public function __construct() {
    $db = $this->DB();

    if(isset($_POST['productName'])) {
        foreach ($_POST as $key => $value) {
            if (ini_get('magic_quotes_gpc'))
                $_POST[$key] = stripslashes($_POST[$key]);
                $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
        }
        $this->AddProduct();
    }
  }

  public function AddProduct() {
    $sSQL = "INSERT INTO ".PREFIX."product (productName, productPrice) 
                VALUES (:productName,:productPrice)";
    $query = $this->db->prepare($sSQL);
    $query->execute(array(
        ":productName" => $_POST['productName'],
        ":productPrice" => $_POST['productPrice']
    )); 
  }
}

Using query parameters is enough to make it secure against SQL injection vulnerability.

The code that calls htmlspecialchars and strip_tags is not relevant to SQL injection. It might be called for to prevent Cross-Site Scripting vulnerabilities, but that's a separate issue. I don't recommend doing those steps as you insert data into the database. Just filter against XSS vulnerabilities when you output to HTML. Otherwise, you get literal & sequences stored in your database, and that's premature. You aren't necessarily going to use the data to display in HTML every time. Just encode it when you output, not when you input.

I never bother with compensating for the possible magic_quotes_gpc. Test for it when you deploy your app, and abort the deployment. It's not valid for any PHP instance to set magic_quotes_gpc in 2014.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM