pg_escape_string到底能做什么? [英] Whats does pg_escape_string exactly do?

查看:63
本文介绍了pg_escape_string到底能做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下脚本,该脚本从html表单获取数据并将其存储在Postgres数据库中。有一个pg_escape_string函数,用于将表单中的值存储到php变量中。在整个网络中搜索时,我发现pg_escape_string转义了要插入数据库的字符串。我对此不太清楚。它实际上逸出了什么?

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>
   <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>


推荐答案

请考虑以下代码:

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

现在假设 $ name 芝加哥奥黑尔 。当您进行字符串插值时,您将获得以下SQL代码:

Now suppose that $name is "Chicago O'Hare". When you do the string interpolation, you get this SQL code:

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

格式错误,因为撇号被解释为 SQL引号,您的查询将出错。

which is ill-formed, because the apostrophe is interpreted as a SQL quote mark, and your query will error.

更糟的事情也可能发生。实际上,MITRE将SQL注入排名为#1 2011年最危险软件错误

Worse things can happen, too. In fact, SQL injection was ranked #1 Most Dangerous Software Error of 2011 by MITRE.

但是无论如何,您都不应该使用字符串插值创建SQL查询。改为使用带有参数的查询

But you should never be creating SQL queries using string interpolation anyway. Use queries with parameters instead.

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

这篇关于pg_escape_string到底能做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆