2011-07-25 24 views
0

http://www.php.net/manual/en/book.mssql.phpPHP和SQL Server如何使它安全?

我正在使用它從LAMP環境連接到SQL Server。我注意到我沒有像準備語句和real_escape_string這樣的neet函數。

如何使我的查詢儘可能安全?任何幫助表示讚賞。

不建議我使用ODBC或PDO,我沒有這個選項。我必須用我擁有的東西來運行,那就是MSSQL。

$con = mssql_connect ('xxx', 'xxx', 'xxx'); 

mssql_select_db('xxx', $con); 

$qry = "SELECT 
      firstname 
    FROM 
      person 
    where firstname = '{$firstname}'"; 

$query = mssql_query($qry, $con); 
+0

@Kerrek:回答一些他的問題。 –

+0

給我一個正確的答案;) – vick

回答

2

不要使用文字,使用的參數和bind他們到您的查詢:

$con = mssql_connect ('xxx', 'xxx', 'xxx'); 
mssql_select_db('xxx', $con); 
$qry = 'SELECT firstname 
    FROM person 
    where firstname = @firstname'; 
mssql_bind ($qry, '@firstname', $firstname, SQLVARCHAR); 
$query = mssql_query($qry, $con); 
+0

根據文檔「mssql_bind-向存儲過程添加參數或向存儲過程添加參數遠程存儲過程「......這不適用於我的情況,因爲它不是存儲過程。 – vick

0

Mssql不提供函數來轉義您的查詢。一種選擇是使用「和addslashes()」來代替,雖然它有點醜陋(並且不包括一切)

這可能會有所幫助:How to escape strings in SQL Server using PHP?

+0

這是如何使它更安全? – vick

+0

它防止SQL注入,這是您對SQL查詢最大的擔憂。 – Chris

+0

不幸的是,addslashes()至多是解決方案的一半(因爲此人已在其他幫助論壇中被告知)。打破addslashes()非常微不足道。 – TML

1

您可以使用htmlentities()將html元素轉換爲html實體,並且此函數接受用於轉義單引號和雙引號的第三個參數。

下面是函數的簽名:

string htmlentities (string $string [, int $flags = ENT_COMPAT [, string $charset [, bool $double_encode = true ]]]) 

和第二參數可以接受的參數:

ENT_COMPAT將其轉換雙引號和獨自離開單引號。

ENT_QUOTES將轉換雙引號和單引號。

ENT_NOQUOTES將保留雙引號和單引號未轉換。

ENT_IGNORE默默地丟棄無效的代碼單元序列,而不是返回空字符串。在PHP 5.3.0中添加。這是爲了向後兼容而提供的;避免使用它,因爲它可能有安全隱患。

您可以簡單地使用addslashes()htmlentities()

,也存在與清洗另一個功能HTML代碼這是場標記出來filter_var()和這樣的例子看是:

$ return_value = filter_var($data_to_be_filtered,FILTER_SANITIZE_STRING);

重要

不要忘記檢查magic_quotes是否啓用。您可以通過書面形式是:

if(get_magic_quotes_gpc()) 
    //do something 

更多magic_quotes的:http://www.php.net/manual/en/info.configuration.php#ini.magic-quotes-gpc

編輯:

您可以通過使用準備好的語句做更安全的交易。他們防止SQL注入。

示例代碼:

$db = new mysqli(); 
$db->real_connect($host,$username,$password,$db) or die("Cannot connect"); 
$query = "select name from users where id = ?"; 
$st = $db->prepare($query); //faster than normal query run 
$st->bind_param("d",$id); 
$st->execute(); 
$st->bind_result($name); 
$st->fetch(); 
echo $name;