我的网站上的评论框功能已经有一段时间了,直到昨天我注意到我的网站上出现了一条看起来不正常的奇怪评论时,这一切都很棒。我的问题是如何防止 SQL 注入攻击/恶意垃圾邮件等。
我不是 PHP 方面的大专家,我确信有某事。就安全性而言,我的代码中缺少。
我介绍了一些基本的验证功能来检查值是否不为空、不包含辱骂性语言、是否有一定的长度等。
我还可以在下面的代码中改进什么以使其对任何攻击更加安全?
<?php
session_start();
require('execute.php');
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(empty($_POST['name']))
{echo '<p style="color:red;"><b>Please provide a valid name</b></p>';}
else
{
$fn = mysqli_real_escape_string($dbc, trim($_POST['name']));
}
if(empty($_POST['comment']))
{echo '<p style="color:red;"><b>Please provide a valid comment</b></p>';}
else
{
$cm = mysqli_real_escape_string($dbc, trim($_POST['comment']));
}
$minimum_n = '/[a-zA-Z]{3,}/';
if(!preg_match($minimum_n, $_POST['name']))
{$_POST['name'] = NULL; echo '<p style="color:red;"><b>Your name is too short or has incorrect format</b></p>';}
$minimum_c = '/[a-zA-Z]{5,}/';
if(!preg_match($minimum_c, $_POST['comment']))
{$_POST['comment'] = NULL; echo '<p style="color:red;"><b>Your message is too short or in incorrect format</b></p>';}
$pattern = '/(shit|crap|http|href)(s|ed|ing|ty|off)?/i'; /* Removed offensive words */
if(preg_match($pattern, $_POST['name']))
{$_POST['name'] = NULL; echo '<p style="color:red;"><b>You have chosen inappropriate nickname. Please use a different one</b></p>';}
if(preg_match($pattern, $_POST['comment']))
{$_POST['comment'] = NULL; echo '<p style="color:red;"><b>You have used inappropriate word(s) in your message</b></p>';}
if(!empty($_POST['name']) && !empty($_POST['comment']))
{
require('execute.php');
$q = "INSERT INTO comment (name, comment, date)
VALUES ('$fn', '$cm' ,NOW())";
$r = mysqli_query($dbc, $q);
mysqli_close($dbc);
}
}
?>
</div>
<div class="container_16 grid_8 alpha lefter">
<?php
session_start();
require('execute.php');
$q = "SELECT * FROM comment ORDER BY user_id DESC";
$r = mysqli_query($dbc, $q);
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
echo "<p>" . ''. "<b>" . ' ' . $row['id']. ' ' . $row['name'] . ' ' . "</b>". ' ' . $row['comment']. ' ' . $row['date'] . ' ' . "</br>";
}
?>