2011-09-01 38 views
6

我正在使用以下腳本,它從一個html表單中獲取數據並存儲在Postgres數據庫中。有這個pg_escape_string函數,它將表單中的值存儲到php變量中。在整個網絡搜索中,我發現pg_escape_string轉義了一個字符串插入到數據庫中。我對此並不十分清楚。它實際上逃脫了什麼?當它說一個字符串被轉義時實際發生了什麼?pg_escape_string究竟幹什麼?

<html> 
    <head></head> 
    <body>  

<?php 
if ($_POST['submit']) { 
    // attempt a connection 
    $dbh = pg_connect("host=localhost dbname=test user=postgres"); 
    if (!$dbh) { 
     die("Error in connection: " . pg_last_error()); 
    } 

    // escape strings in input data 
    $code = pg_escape_string($_POST['ccode']); 
    $name = pg_escape_string($_POST['cname']); 

    // execute query 
    $sql = "INSERT INTO Countries (CountryID, CountryName) VALUES('$code', '$name')"; 
    $result = pg_query($dbh, $sql); 
    if (!$result) { 
     die("Error in SQL query: " . pg_last_error()); 
    } 

    echo "Data successfully inserted!"; 

    // free memory 
    pg_free_result($result); 

    // close connection 
    pg_close($dbh); 
} 
?>  

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> 
     Country code: <br> <input type="text" name="ccode" size="2"> 
     <p> 
     Country name: <br> <input type="text" name="cname">  
     <p> 
     <input type="submit" name="submit"> 
    </form> 

    </body> 
</html> 

回答

1

pg_escape_string()防止sql injection在你的代碼

+0

這真是太舊了,但對於任何後來遇到此問題的人來說,pg_escape_string()是防禦SQL注入的一種防禦措施,但並未阻止它。使用準備好的語句更好。 (http://stackoverflow.com/questions/732561/why-is-using-a-mysql-prepared-statement-more-secure-than-using-the-common-escape) – pandubear

5

考慮下面的代碼:

$sql = "INSERT INTO airports (name) VALUES ('$name')"; 

現在假設$name"Chicago O'Hare"。當你做對串插,你得到這個SQL代碼:

INSERT INTO airports (name) VALUES ('Chicago O'Hare') 

這是形成不良的,因爲撇號被解釋爲SQL引號,和您的查詢就會報錯。

Worse things也可能發生。實際上,SQL注入被MITRE排列爲#1 Most Dangerous Software Error of 2011

但是,您永遠不應該使用字符串插值創建SQL查詢。改爲使用queries with parameters

$sql = 'INSERT INTO airports (name) VALUES ($1)'; 
$result = pg_query_params($db, $sql, array("Chicago O'Hare")); 
+0

非常感謝您的明確解釋: ) –

+0

它究竟把'芝加哥奧黑爾'改爲'芝加哥奧黑爾'(究竟是如何轉義的取決於你的數據庫設置) – dsas