2014-04-23 21 views
0

美好的一天!在PHP中製作評論部分的安全方式

今天我正在爲我的網站發表評論部分。我知道它不太難做出工作評論部分,但我想使它安全並防止SQL注入。

你有什麼建議,我應該怎麼做,我應該注意什麼?

我會在這裏發表我的想法,以便您可以告訴我哪部分是不安全的。

假設您需要註冊並登錄才能發表評論。

<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> 

這是一些基本的想法,請注意在所有這一切,所以不要說新手上午驚訝,如果你看到不好的東西在這上面的代碼。感謝您的幫助。在這個here

回答

2

0
$comment=filter_input(INPUT_POST,"comment",FILTER_SANITIZE_STRING); 

更多信息我已經重新定義了一些部分。

<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> 
1

在將您的$ comment變量傳遞給查詢字符串之前,您應該替換您的$ comment變量中的MySQL關鍵字。使用filter_input或mysql_real_escape_string函數來防止注入。很奇怪,您可以使用其他方法來執行SQL部分,這是更安全的。