2013-05-13 79 views
-1

我想使這個頁面安全,但我不知道我應該從哪裏開始。因爲我昨天注入了一些資源,所以我逃避了mysql的轉義字符串,但是我沒有太多幫助。我不知道任何有關PDO的事情,你能把我搞定嗎?這是代碼。參數化語句和安全性

<?php 
//category.php 

require_once('startsession.php'); 
require_once('php/mysql_prisijungimas.php'); 
include 'connect.php'; 

//first select the category based on $_GET['cat_id'] 
$sql = "SELECT 
      cat_id, 
      cat_name, 
      cat_description 
     FROM 
      categories 
     WHERE 
      cat_id = " . mysql_real_escape_string($dbc, trim($_GET['id'])); 

$result = mysql_query($sql); 

if(!$result) 
{ 
    echo 'The category could not be displayed, please try again later.' . mysql_error(); 
} 
else 
{ 
    if(mysql_num_rows($result) == 0) 
    { 
     echo 'This category does not exist.'; 
    } 
    else 
    { 
     //display category data 
     while($row = mysql_fetch_assoc($result)) 
     { 
      echo '<h2>Topics in &prime;' . $row['cat_name'] . '&prime; category</h2><br />'; 
     } 

     //do a query for the topics 
     $sql = "SELECT 
        topic_id, 
        topic_subject, 
        topic_date, 
        topic_cat 
       FROM 
        topics 
       WHERE 
        topic_cat = " . mysql_real_escape_string($dbc, trim($_GET['id'])); 

     $result = mysql_query($sql); 

     if(!$result) 
     { 
      echo 'The topics could not be displayed, please try again later.'; 
     } 
     else 
     { 
      if(mysql_num_rows($result) == 0) 
      { 
       echo 'There are no topics in this category yet.'; 
      } 
      else 
      { 
       //prepare the table 
       echo '<table border="1"> 
         <tr> 
         <th>Topic</th> 
         <th>Created at</th> 
         </tr>'; 

       while($row = mysql_fetch_assoc($result)) 
       {    
        echo '<tr>'; 
         echo '<td class="leftpart">'; 
          echo '<h3><a href="topic.php?id=' . $row['topic_id'] . '">' . $row['topic_subject'] . '</a><br /><h3>'; 
         echo '</td>'; 
         echo '<td class="rightpart">'; 
          echo date('d-m-Y', strtotime($row['topic_date'])); 
         echo '</td>'; 
        echo '</tr>'; 
       } 
      } 
     } 
    } 
} 
?> 
+0

那麼這將無法與MySQL的擴展。 PDO支持[預先準備的語句](http://php.net/manual/en/pdo.prepared-statements.php) – 2013-05-13 14:12:24

+0

[偉大的逃避現實(或:你需要知道如何處理文本中的文本)](http ://kunststube.net/escapism/) – deceze 2013-05-13 14:27:32

回答

1

在你的情況下環繞mysql_real_escape_string加上引號,像這樣:

SELECT * FROM table WHERE ID = '".mysql_real_escape_String($_POST['ID'])."' 

注意額外的單引號。這將使它更安全,但使用準備好的語句更好。除了喜歡在mysql_query上使用預處理語句外,從php版本5.5.0開始,函數mysql_query()將被棄用。

在stackoverflow上還有另一個主題,它提出了「如何防止PHP Pdo中的SQL注入」問題。你可能會發現一些樣本和額外的信息: How can I prevent SQL injection in PHP?

+0

謝謝你的幫助。 – 2013-05-13 15:02:31