postgresql pg_escape_string 究竟是做什么的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7266090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Whats does pg_escape_string exactly do?
提问by Sri Hari Charan
I'm using the following script which takes the data from a html form and stores in a Postgres DB. There is this pg_escape_string function which stores the value from the form to the php variable. Searching the web throughout, I found that pg_escape_string escapes a string for insertion into the database. I'm not much clear on this. What does it actually escaping? What actually happens when its said that a string is escaped?
我正在使用以下脚本,它从 html 表单中获取数据并存储在 Postgres 数据库中。有这个 pg_escape_string 函数将表单中的值存储到 php 变量。在整个网络上搜索,我发现 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>
回答by Ryan Culpepper
Consider the following code:
考虑以下代码:
$sql = "INSERT INTO airports (name) VALUES ('$name')";
Now suppose that $name
is "Chicago O'Hare"
. When you do the string interpolation, you get this SQL code:
现在假设$name
是"Chicago O'Hare"
。当您进行字符串插值时,您会得到以下 SQL 代码:
INSERT INTO airports (name) VALUES ('Chicago O'Hare')
which is ill-formed, because the apostropheis interpreted as a SQL quote mark, and your query will error.
这是格式错误的,因为撇号被解释为SQL 引号,并且您的查询将出错。
Worse thingscan happen, too. In fact, SQL injection was ranked #1 Most Dangerous Software Error of 2011by MITRE.
更糟糕的事情也可能发生。事实上,SQL 注入被MITRE评为2011 年最危险的软件错误第一名。
But you should never be creating SQL queries using string interpolation anyway. Use queries with parametersinstead.
但是无论如何您都不应该使用字符串插值来创建 SQL 查询。请改用带参数的查询。
$sql = 'INSERT INTO airports (name) VALUES ()';
$result = pg_query_params($db, $sql, array("Chicago O'Hare"));
回答by tttony
pg_escape_string()prevent sql injectionin your code
pg_escape_string()防止代码中的sql 注入