2013-05-16 22 views
7

我正在使用OSCommerce與MySQL的項目,我很困惑,因爲我應該使用tep_db_input()或tep_db_prepare_input()。我假設我應該使用tep_db_input()圍繞正在插入/更新的任何字符串,但是何時應該使用其他函數?OSCommerce tep_db_input vs tep_db_prepare_input

例如,如果我是從數據庫中選擇一些數據,並根據結果再INSERT一行到另一張表,我需要在某一時刻準備輸入?或者只是再次使用tep_db_input?

$width = '3"'; // 3 inches 
$new_height = '3\' 5"'; // 3 feet 5 inches 

$result = tep_db_query(
    "SELECT height 
    FROM measurements 
    WHERE width = '".tep_db_input($width)."'" 
); 

while ($row = tep_db_fetch_array($result)) { 
    tep_db_query(
     "INSERT INTO measurement_history (
      field, 
      old_value, 
      new_value 
     ) VALUES (
      'height', 
      '".tep_db_input($row['height'])."', 
      '".tep_db_input($new_height)."' 
     )" 
    ); 
} 

這是正確的嗎?

編輯::如果有些人不熟悉這些功能,這裏是他們的定義:

function tep_sanitize_string($string) { 
    $patterns = array ('/ +/','/[<>]/'); 
    $replace = array (' ', '_'); 
    return preg_replace($patterns, $replace, trim($string)); 
} 

function tep_db_input($string, $link = 'db_link') { 
    global $$link; 

    if (function_exists('mysql_real_escape_string')) { 
     return mysql_real_escape_string($string, $$link); 
    } elseif (function_exists('mysql_escape_string')) { 
     return mysql_escape_string($string); 
    } 

    return addslashes($string); 
} 

function tep_db_prepare_input($string) { 
    if (is_string($string)) { 
     return trim(tep_sanitize_string(stripslashes($string))); 
    } elseif (is_array($string)) { 
     reset($string); 
     while (list($key, $value) = each($string)) { 
      $string[$key] = tep_db_prepare_input($value); 
     } 
     return $string; 
    } else { 
     return $string; 
    } 
} 

回答

6

tep_db_input使用mysql_real_escape_stringmysql_escape_string,這就是準備數據庫輸入一個推薦的方式。 (我猜這個功能將使用mysqli_real_escape_string()或similiar在以後的版本,因爲mysql_real_escape_string將開始使用PHP 5.5.0被棄用。)

凡tep_db_input與mysql_real_escape_string只是沒有逃脫:

mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, 
which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a. 

tep_db_prepare_input做了不同的事情,例如修剪空格和替換括號,並通過調用stripslashes來取消(!)。

所以我的建議是:總是使用tep_db_input。如果你使用tep_db_prepare_input來清除空白等,那麼也可以使用tep_db_input。

1

這有點奇怪,但你使用兩者。這樣做將防止惡意用戶的攻擊,以及來自異常輸入的意外問題。

對來自HTML表單的任何輸入數據使用tep_db_prepare輸入。這清除了HTML,魔術引號和腳本注入的問題。不要在從數據庫中檢索到的文本中使用它。

然後,在將其寫入數據庫之前使用tep_db_input。這將轉義MySQL字符以防止SQL注入攻擊和其他此類問題。

下面是一個代碼示例,演示它:

$clean = tep_db_prepare_input($_POST['name']); 
$query_text = tep_db_query("select * from " . TABLE_NAME . " where name='" . tep_db_input($clean) . "'");