简体   繁体   English

PHP从Web窗体安全地将数据插入MySql

[英]Php Insert Data To MySql From Web Form Securely

I am learning php and have been following the OOP creating a data class tutorial at phpbridge.org 我正在学习php,并且一直在OObridge上通过phpbridge.org创建数据类教程

In the tutorial they take form data from a post and insert it into the database. 在本教程中,他们从帖子中获取表单数据并将其插入数据库中。

Here is the code: 这是代码:

Step 1: The Form 步骤1:表格

<h2>New Topic</h2>
<form action="add.php" method="POST">
    <label>
        Title: <input type="text" name="title">
    </label>
    <br>
    <label>
        Description:
        <br>
        <textarea name="description" cols="50" rows="20"></textarea>
    </label>
    <br>
    <input type="submit" value="Add Topic">
</form>

Step 2 Php file 步骤2的php文件

<?php
 require 'TopicData.php';

if (isset($_POST) && sizeof($_POST) > 0) {
    $data = new TopicData();
    $data->add($_POST);
}
?>

Step 3 第三步

The Function included in TopicData.php TopicData.php中包含的函数

public function add($data)
{
    $query = $this->connection->prepare(
        "INSERT INTO topics (
            title,
            description
        ) VALUES (
            :title,
            :description
        )"
    );

    $data = [
        ':title' => $data['title'],
        ':description' => $data['description']
    ];

    $query->execute($data);
}

My question is in regards to security. 我的问题是关于安全性的。 Before this data is inserted into a database wouldn't it be best practice to run each field of the form through the filter_input() function? 在将这些数据插入数据库之前,最好的做法是通过filter_input()函数运行表单的每个字段吗? Also should these be run through filter_var() as well? 还应该通过filter_var()运行它们吗?

If this is necessary what exactly would the filter code look like? 如果有必要,过滤器代码将是什么样子?

Thanks! 谢谢!

The TopicData.php file is using prepared SQL queries. TopicData.php文件正在使用准备好的SQL查询。 The benefit of using prepared queries is that it removes the possibility of SQL Injection provided that the SQL query is not based on external input. 使用准备好的查询的好处是,只要SQL查询不基于外部输入,它就消除了SQL注入的可能性。 When using prepared queries, the template of the query is sent separately from the data. 使用准备好的查询时,查询模板与数据分开发送。 This has many benefits which are described here: https://www.w3schools.com/php/php_mysql_prepared_statements.asp 这具有许多好处,在这里进行了描述: https : //www.w3schools.com/php/php_mysql_prepared_statements.asp

It removes the need for sanitizing form data. 它消除了对表单数据进行清理的需要。 However the form data may still need to be filtered using the filter_var functions, if validation is required such as maximum string length, maximum and minimum values etc. 但是,如果需要验证,例如最大字符串长度,最大和最小值等,则仍可能需要使用filter_var函数对表单数据进行过滤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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