php - 在 PHP 中制作评论部分的安全方法

标签 php html mysql comments

美好的一天!

今天我正在为我的网站设计评论部分。我知道制作有效的评论部分并不难,但我想让它安全并防止 sql 注入(inject)。

您有什么建议,我应该怎么做,我应该注意什么?

我会在这里发布我的想法,这样你就可以告诉我哪一部分是不安全的。

假设您需要注册并登录才能发表评论。

<html>
<head>
require 'connect.inc.php';
require 'function.php';
</head>
<body>

<?php
if(loggedin()){
$id = $_SESSION['user_id']; //loggedin function check if user is logged in

if(isset($_POST['comment_button'])){
$comment = $_POST['comment'];

mysql_query("INSERT INTO comments  VALUES('','$id','$comment')");
}
?>

<form>
Comment:<br>
<textarea name='comment'></textarea>
<input type="submit" name="comment_button" value="Login"/>
</form>

<?php 
}else{header('location: index.php');
} ?>

</body>
</html>

这是一些基本的想法,请注意,我是所有这些方面的新手,所以如果您在上面的代码中看到不好的地方,请不要感到惊讶。感谢您的帮助。

最佳答案

我重新设计了部分内容。

 <html>
 <head>
 <?php
   require 'connect.inc.php';
   require 'function.php';
 ?>
 </head>
 <body>

 <?php
 if(loggedin())
 {
    $id = $_SESSION['user_id']; //loggedin function check if user is logged in

    if(isset($_POST['comment_button']))
    {
      $mysqli = new mysqli('localhost', 'user', 'password', 'mysampledb');

    /* check connection */
    if (mysqli_connect_errno()) {
      printf("Connect failed: %s\n", mysqli_connect_error());
      exit();
    }

    $stmt = $mysqli->prepare("INSERT INTO comments VALUES (?,?,?)");
    $stmt->bind_param('sss', '', '$id', '$comment');   // bind to the parameter

    // escape the POST data for added protection
    $comment = isset($_POST['comment'])
      ? $mysqli->real_escape_string($_POST['comment'])
      : '';

   /* execute prepared statement */
   $stmt->execute();

   printf("%d Comment added successfully.\n", $stmt->affected_rows);

  /* close statement and connection */
  $stmt->close();

  /* close connection */
  $mysqli->close();

}
?>

<form>
Comment:<br>
<textarea name='comment'></textarea>
<input type="submit" name="comment_button" value="Login"/>
</form>

<?php 
}else{header('location: index.php');
} ?>

</body>
</html>

关于php - 在 PHP 中制作评论部分的安全方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23242966/

相关文章:

PHP:使用外部连接文件时关闭mysql连接

jquery - 在触摸设备上禁用 jQuery 滚动条插件?

php - 通过 JSON 将分隔字符串发送到 PHP 以获取准备好的语句

PHP 使用 PDO 和 PDO 语句

javascript - 在动态创建的单选按钮选择上显示 Div (PHP-AJAX)

php - 在 Symfony2 的 postPersist 和 postUpdate 实体上创建静态文件

php - 难以使用 payum Bundle 管理数据

css - fiddle 工作,真实页面不在 IE9 中

html - 在 Firefox 中使用 bootstrap 3.3.5 的 glyphicons 有一些问题

mysql - 有没有办法在所有数据库的sql server中作为整数工作