sql - Secure comment box in PHP -
i have had comment box function on website while , grand until yesterday when noticed bizarre comment appear on website didn't normal. question here how prevent sql injection attacks/ malicious spam etc.
i not big expert on php , i'm sure there sth. missing in code in terms of security.
i have introduced basic validation functions check if values not empty, not contain abusive language, of length etc.
what else improve in below code make more secure attacks?
<?php session_start(); require('execute.php'); if($_server['request_method'] == 'post') { if(empty($_post['name'])) {echo '<p style="color:red;"><b>please provide 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 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 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 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 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 message</b></p>';} if(!empty($_post['name']) && !empty($_post['comment'])) { require('execute.php'); $q = "insert 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 * comment order 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>"; } ?>
caution security: default character set
the character set must set either @ server level, or api function mysqli_set_charset() affect mysqli_real_escape_string(). see concepts section on character sets more information.
that's php manual said mysqli_real_escape_string function. try set proper charset mysqli_set_charset() function.
Comments
Post a Comment