PHP
downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

mysql_result> <mysql_query
Last updated: Fri, 10 Jul 2009

view this page in

mysql_real_escape_string

(PHP 4 >= 4.3.0, PHP 5)

mysql_real_escape_stringSQL 文中で用いる文字列の特殊文字をエスケープする

説明

string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier ] )

現在の接続の文字セットで unescaped_string の特殊文字をエスケープし、 mysql_query() で安全に利用できる形式に変換します。バイナリデータを挿入しようとしている場合、 必ずこの関数を利用しなければなりません。

mysql_real_escape_string() は、MySQL のライブラリ関数 mysql_real_escape_string をコールしています。 これは以下の文字について先頭にバックスラッシュを付加します。 \x00, \n, \r, \, ', " そして \x1a.

データの安全性を確保するため、MySQL へクエリを送信する場合には (わずかな例外を除いて)常にこの関数を用いなければなりません。

パラメータ

unescaped_string

エスケープされる文字列。

link_identifier

MySQL 接続。 指定されない場合、mysql_connect() により直近にオープンされたリンクが 指定されたと仮定されます。そのようなリンクがない場合、引数を指定せずに mysql_connect() がコールした時と同様にリンクを確立します。 リンクが見付からない、または、確立できない場合、 E_WARNING レベルのエラーが生成されます。

返り値

成功した場合にエスケープ後の文字列、失敗した場合に FALSE を返します。

例1 単純な mysql_real_escape_string() の例

<?php
// 接続
$link mysql_connect('mysql_host''mysql_user''mysql_password')
    OR die(
mysql_error());

// クエリ
$query sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
            
mysql_real_escape_string($user),
            
mysql_real_escape_string($password));
?>

例2 SQL インジェクション攻撃の例

<?php
// データベース上のユーザに一致するかどうかを調べる
$query "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);

// $_POST['password'] をチェックしなければ、このような例でユーザに望みどおりの情報を取得されてしまう
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";

// MySQL に送信されたクエリは、
echo $query;
?>

MySQL に送信されたクエリは次のとおり:

SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''

これでは、パスワードを知らなくても誰でもログインできてしまいます。

注意

注意: mysql_real_escape_string() を利用する前に、MySQL 接続が確立されている必要があります。もし存在しなければ、 E_WARNING レベルのエラーが生成され、FALSE が返されます。link_identifier が指定されなかった場合は、 直近の MySQL 接続が用いられます。

注意: magic_quotes_gpc が有効な場合は、 まず最初に stripslashes() を適用します。そうしないと、 すでにエスケープされているデータに対してさらにエスケープ処理を してしまうことになります。

注意: この関数を用いてデータをエスケープしなければ、クエリは SQL インジェクション攻撃 に対しての脆弱性を持ったものになります。

注意: mysql_real_escape_string()%_ をエスケープしません。 MySQL では、これらの文字を LIKE, GRANT, または REVOKE とともに用いることで、 ワイルドカードを表現します。

参考



mysql_result> <mysql_query
Last updated: Fri, 10 Jul 2009
 
add a note add a note User Contributed Notes
mysql_real_escape_string
info at saturnprods dot com
13-Jun-2009 07:37
I always use this function so I don't have to retype over and over the mysql_real_escape_string function.

<?php
function safe($value){
   return
mysql_real_escape_string($value);
}
?>

Then, when I am using my code, I simply use:

<?php
$name
= safe($_POST["name"]);
$password = safe($_POST["password"]);
?>
kendsnyder at gmail dot com
25-Mar-2009 09:07
<?php

// Here is a simple named binding function for queries that makes SQL more readable:
// $sql = "SELECT * FROM users WHERE user = :user AND password = :password";
// mysql_bind($sql, array('user' => $user, 'password' => $password));
// mysql_query($sql);

function mysql_bind(&$sql, $vals) {
    foreach (
$vals as $name => $val) {
       
$sql = str_replace(":$name", "'" . mysql_real_escape_string($val) . "'", $sql);
    }
}

?>
Bastiaan Welmers
24-Mar-2008 07:46
This function won't help you when inserting binary data, to me it will get mallformed into the database. Probably UTF-8 combinations will be translated by this function or somewhere else when inserting data when running mysql in UTF-8 mode.

A better way to insert binary data is to transfer it to hexadecimal notation like this example:

<?php
$string
= $_REQUEST['string'];
$binary = file_get_contents($_FILE['file']['tmp_name']);

$string = mysql_real_escape_string($string);
$binary_hex = bin2hex($binary);

$query = "INSERT INTO `table` (`key`, `string`, `binary`, `other`) VALUES (NULL, '$string', 0x$binary_hex, '$other')";

?>
Anonymous
03-Mar-2008 06:57
My escape function:

Automatically adds quotes (unless $quotes is false), but only for strings. Null values are converted to mysql keyword "null", booleans are converted to 1 or 0, and numbers are left alone. Also can escape a single variable or recursively escape an array of unlimited depth.

<?php
function db_escape($values, $quotes = true) {
    if (
is_array($values)) {
        foreach (
$values as $key => $value) {
           
$values[$key] = db_escape($value, $quotes);
        }
    }
    else if (
$values === null) {
       
$values = 'NULL';
    }
    else if (
is_bool($values)) {
       
$values = $values ? 1 : 0;
    }
    else if (!
is_numeric($values)) {
       
$values = mysql_real_escape_string($values);
        if (
$quotes) {
           
$values = '"' . $values . '"';
        }
    }
    return
$values;
}
?>
matthijs at yourmediafactory dot com
27-Dec-2007 09:49
In response to Michael D - DigitalGemstones.com:

Check the example again: sprintf(%d) already does the int conversion for you, so it's both perfectly save as well as more elegant than manually casting.
user at NOSPAM dot example dot com
28-Aug-2007 12:16
if you're doing a mysql wildcard query with
LIKE, GRANT, or REVOKE
you may use addcslashes to escape the string:

<?php
$param
= mysql_real_escape_string($param);
$param = addcslashes($param, '%_');
?>
brian dot folts at gmail dot com
06-Sep-2006 04:25
mysql_real_escape_string is a bit annoying when you need to do it over an array.

<?php
function mysql_real_escape_array($t){
    return
array_map("mysql_real_escape_string",$t);
}
?>

this one just mysql_real_escape's the whole array.

ex) <?php $_POST=mysql_real_escape_array($_POST); ?>

and then you dont have to worry about forgetting to do this.
kael dot shipman at DONTSPAMIT! dot gmail dot com
18-Jul-2006 08:19
It seems to me that you could avoid many hassels by loading valid database values into an array at the beginning of the script, then instead of using user input to query the database directly, use it to query the array you've created. For example:

<?php
//you still have to query safely, so always use cleanup functions like eric256's
$categories = sql_query("select catName from categories where pageID = ?",$_GET['pageID']);
while (
$cts = @mysql_fetch_row($categories)) {
 
//making $cts both the name and the value of the array variable makes it easier to check for in the future.
 //obviously, this naming system wouldn't work for a multidimensional array
 
$cat_ar[$cts[0]] = $cts[0];
}
...

//user selects sorting criteria
//this would be from a query string like '?cats[]=cha&cats[]=fah&cats[]=lah&cats[]=badValue...', etc.
$cats = $_GET['cats'];

//verify that values exist in database before building sorting query
foreach($cats as $c) {
 if (
$cat_ar[$c]) { //instead of in_array(); maybe I'm just lazy... (see above note)
 
$cats1[] = "'".mysql_real_escape_string($c)."'";
 }
}
$cats = $cats1;
//$cats now contains the filtered and escaped values of the query string

$cat_query = '&& (category_name = \''.implode(' || category_name = \'',$cats).'\')';
//build a sql query insert
//$cat_query is now "&& (category_name = 'cha' || category_name = 'fah' || category_name = 'lah')" - badValue has been removed
//since all values have already been verified and escaped, you can simply use them in a query
//however, since $pageID hasn't been cleaned for this query, you still have to use your cleaning function
$items = sql_query("SELECT * FROM items i, categories c WHERE i.catID = c.catID && pageID = ? $cat_query", $pageID);
nicolas
30-May-2006 08:38
Note that mysql_real_escape_string doesn't prepend backslashes to \x00, \n, \r, and and \x1a as mentionned in the documentation, but actually replaces the character with a MySQL acceptable representation for queries (e.g. \n is replaced with the '\n' litteral). (\, ', and " are escaped as documented) This doesn't change how you should use this function, but I think it's good to know.

mysql_result> <mysql_query
Last updated: Fri, 10 Jul 2009
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites