这段代码对SQL注入安全吗? [英] Is this code safe from SQL injection

查看:56
本文介绍了这段代码对SQL注入安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使我的代码尽可能免受任何类型的攻击,我希望对下面使用的简单代码有所了解.关于如何使它更容易受到攻击的任何指示,以及为什么会如此出色.我已经读到,使用准备好的语句是防止攻击的最佳实践.

I want to make my code as safe as possible from any type of attack I was hoping for some insight on the simple code I am using below. Any pointers on how to make it safer if it is vulnerable and why would be awesome. I have read that using prepared statements is the best practice to safeguard against attacks.

<?php 

    try {
    $conn = new PDO('mysql:host=localhost;dbname=test', 'user', 'XXXXX');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare('INSERT INTO people (name, email) VALUES (:name, :email)');

    $stmt->execute(array(':name' => $_POST['name'], ':email' => $_POST['email']));

    #If one or more rows were returned...

    } catch(PDOException $e){
        echo'ERROR: ' . $e->getMessage();
    }
    echo "Added $_POST[name] with email $_POST[email] succsessfully";
    $conn = null;
    ?>

推荐答案

看起来您可以安全地进行SQL注入,但是您现在在回显中遇到了XSS问题.确保在回显用户输入之前始终对其进行清理/转义.

It looks like you're safe from SQL injection, but you now have issues with XSS in your echo. Make sure you always sanitize / escape user input before its echo'd.

echo "Added $_POST[name] with email $_POST[email] succsessfully";

应该成为

echo "Added" . htmlspecialchars($_POST['name']) . "with email" . htmlspecialchars($_POST['email']) . "succsessfully";

这篇关于这段代码对SQL注入安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆