防止以输入形式执行代码

时间:2018-01-26 18:06:15

标签: jquery forms

我一直在寻找负荷。但似乎没有任何效果。我有一个论坛的输入表格。但是,我知道您可以将代码从html输入到SQL。我想知道如何防止这种情况显然这对于​​能够使用的人来说是毁灭性的。感谢您提供任何帮助和建议。

<form id="form1" name="form1" method="post" action="add_topic.php">
<table>
<tr>
<td><strong>Create New Topic</strong></td>
</tr>
<tr>
<td><strong>Topic</strong></td>
<td><textarea maxlength="140" name="topic" type="text" id="topic" size="50" required/></textarea></td>
</tr>
<tr>
<td><strong>Detail</strong></td>
<td><textarea maxlength="655" name="detail" cols="50" rows="3" id="detail" required></textarea></td>
</tr>
<tr style="display: none;">
<td><strong>Name</strong></td>
<td><input name="name" type="text" id="name" size="50" value="<?php echo $_SESSION['username'];?>" readonly/></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input class="submit" type="submit" name="Submit" value="Submit" /> <input class="submit2" type="reset" style="float: right;" name="Submit2" value="Delete All" /></td>
</tr>
</table>
</td>
</form>

如何实现此代码的某些功能,以防止在我的表单中提交可能影响我的网站的代码。感谢。

2 个答案:

答案 0 :(得分:1)

从用户界面可以做任何事情,您应该使用某些格式化程序(preg_replace,散列等)处理服务器上的代码。

并使用一些 ORM 完成它,以便在sql上执行一些“预处理语句”。它将格式化并准备您的输入以避免类似

"select x from y where $filter"

来了

"select x from y where col01 = :val1 and col02 = :val2"

php

的示例
<?php
 $pdo = new PDO('mysql:host=localhost;dbname=crud', 'root', '');
 $stmt = $pdo->prepare('select * from agenda where nome = :nome');
 $stmt->bindValue(':nome', 'kalil');
 $run = $stmt->execute();
 $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);
?>

HTML5 ,您可以格式化为更好的视觉效果:

<form action="/action_page.php">
Country code: <input type="text" name="country_code" 
pattern="[A-Za-z]{3}" title="Three letter country code">
<input type="submit">
</form>

在Ajax中, Jquery

我认为你可以看到A simple jQuery form validation script,非常好

答案 1 :(得分:1)

理想情况下,您应该在服务器端而不是客户端进行更改,即HTML。

因此您应该使用预准备语句来构建将自动转义输入的sql查询,以便它不会执行用户提供的sql命令。 对于PHP,你可以像mysqli一样做什么

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name); // 's' specifies the variable type => 'string'

$stmt->execute();

XSS更新

上面的代码是为了防止Sql注入。如果要显示从Db到前端(浏览器)的内容,您可以转义HTML字符并存储在Db中,这样它也会阻止XSS

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', htmlspecialchars($name) ); // 's' specifies the variable type => 'string'

$stmt->execute();

快乐编码