mysql_real_escape_string

(PHP 4 >= 4.3.0, PHP 5)

mysql_real_escape_stringEscapa caracteres especiales en una cadena para su uso en una sentencia SQL

Advertencia

Esta extensión fue declarada obsoleta en PHP 5.5.0 y eliminada en PHP 7.0.0. En su lugar debería utilzarse las extensiones MySQLi o PDO_MySQL. Véase también la guía MySQL: elegir una API. Las alternativas a esta función son:

Descripción

mysql_real_escape_string(string $unescaped_string, resource $link_identifier = NULL): string

Escapa caracteres especiales en la cadena dada por unescaped_string, teniendo en cuenta el conjunto de caracteres en uso de la conexión, para que sea seguro usarla en mysql_query(). Si se van a insertar datos binarios, se ha de usar esta función.

mysql_real_escape_string() llama a la función mysql_real_escape_string de la biblioteca de MySQL, la cual antepone barras invertidas a los siguientes caracteres: \x00, \n, \r, \, ', " y \x1a.

Esta función siempre debe usarse (con pocas excepciones) para hacer seguros los datos antes de enviar una consulta a MySQL.

Precaución

Seguridad: el conjunto de caracters predeterminado

El conjunto de caracteres debe ser establecido o bien a nivel del servidor, o bien con la función mysql_set_charset() de la API para que afecte a mysql_real_escape_string(). Véase la sección sobre los conceptos de conjuntos de caracters para más información.

Parámetros

unescaped_string

La cadena a escapar.

link_identifier

La conexión MySQL. Si no se especifica el identificador de enlace, se asume el último enlace abierto por mysql_connect(). Si no se encuentra este enlace, se intentará crear un nuevo enlace como si mysql_connect() hubiese sido invocada sin argumentos. Si no se encuentra o establece ninguna conexión, se genera un error de nivel E_WARNING.

Valores devueltos

Devuelve la cadena escapada, o false en caso de error.

Errores/Excepciones

Ejecutar esta función sin una conexión de MySQL presente también emitirá errores de nivel E_WARNING de PHP. Solo se ha de ejecutar con una conexión de MySQL válida presente.

Ejemplos

Ejemplo #1 Ejemplo sencillo de mysql_real_escape_string()

<?php
// Conexión
$enlace = mysql_connect('anfitrión_mysql', 'usuario_mysql', 'contraseña_mysql')
OR die(
mysql_error());

// Consulta
$consulta = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($usuario),
mysql_real_escape_string($contraseña));
?>

Ejemplo #2 mysql_real_escape_string() requiere una conexión

Este ejemplo muestra lo que sucede si no hay presente una conexión de MySQL al invocar a esta función.

<?php
// No nos hemos conectado a MySQL

$apellido = "O'Reilly";
$_apellido = mysql_real_escape_string($apellido);

$consulta = "SELECT * FROM actors WHERE last_name = '$_apellido'";

var_dump($_apellido);
var_dump($consulta);
?>

El resultado del ejemplo sería algo similar a:

Warning: mysql_real_escape_string(): No such file or directory in /this/test/script.php on line 5
Warning: mysql_real_escape_string(): A link to the server could not be established in /this/test/script.php on line 5

bool(false)
string(41) "SELECT * FROM actors WHERE last_name = ''"

Ejemplo #3 Un ejemplo de ataque de inyección de SQL

<?php
// No hemos comprobado $_POST['password'], ¡podría ser cualquier cosa que el usuario quisiera! Por ejemplo:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";

// Consultar la base de datos para comprobar si existe algún usuario que coincida
$consulta = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($consulta);

// Esto significa que la consulta enviada a MySQL sería:
echo $consulta;
?>

La consulta enviada a MySQL:

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

Esto permitiría a alguien acceder a una sesión sin una contraseña válida.

Notas

Nota:

Se requiere una conexión a MySQL antes de usar mysql_real_escape_string(), si no, se generará un error de nivel E_WARNING, y se devolverá false. Si link_identifier no está definido, se usará la última conexión a MySQL.

Nota:

Si esta función no se utiliza para escapar los datos, la consulta es vulnerable a Ataques de inyección SQL.

Nota: mysql_real_escape_string() no escapa % ni _. Estos son comodines en MySQL si se combinan con LIKE, GRANT, o REVOKE.

Ver también

add a note

User Contributed Notes 6 notes

up
183
feedr
13 years ago
Just a little function which mimics the original mysql_real_escape_string but which doesn't need an active mysql connection. Could be implemented as a static function in a database class. Hope it helps someone.

<?php
function mysql_escape_mimic($inp) {
if(
is_array($inp))
return
array_map(__METHOD__, $inp);

if(!empty(
$inp) && is_string($inp)) {
return
str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp);
}

return
$inp;
}
?>
up
31
nicolas
18 years ago
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.
up
22
Walter Tross
12 years ago
For further information:
http://dev.mysql.com/doc/refman/5.5/en/mysql-real-escape-string.html
(replace your MySQL version in the URL)
up
8
sam at numbsafari dot com
11 years ago
No discussion of escaping is complete without telling everyone that you should basically never use external input to generate interpreted code. This goes for SQL statements, or anything you would call any sort of "eval" function on.

So, instead of using this terribly broken function, use parametric prepared statements instead.

Honestly, using user provided data to compose SQL statements should be considered professional negligence and you should be held accountable by your employer or client for not using parametric prepared statements.

What does that mean?

It means instead of building a SQL statement like this:

"INSERT INTO X (A) VALUES(".$_POST["a"].")"

You should use mysqli's prepare() function (http://php.net/manual/en/mysqli.prepare.php) to execute a statement that looks like this:

"INSERT INTO X (A) VALUES(?)"

NB: This doesn't mean you should never generate dynamic SQL statements. What it means is that you should never use user-provided data to generate those statements. Any user-provided data should be passed through as parameters to the statement after it has been prepared.

So, for example, if you are building up a little framework and want to do an insert to a table based on the request URI, it's in your best interest to not take the $_SERVER['REQUEST_URI'] value (or any part of it) and directly concatenate that with your query. Instead, you should parse out the portion of the $_SERVER['REQUEST_URI'] value that you want, and map that through some kind of function or associative array to a non-user provided value. If the mapping produces no value, you know that something is wrong with the user provided data.

Failing to follow this has been the cause of a number of SQL-injection problems in the Ruby On Rails framework, even though it uses parametric prepared statements. This is how GitHub was hacked at one point. So, no language is immune to this problem. That's why this is a general best practice and not something specific to PHP and why you should REALLY adopt it.

Also, you should still do some kind of validation of the data provided by users, even when using parametric prepared statements. This is because that user-provided data will often become part of some generated HTML, and you want to ensure that the user provided data isn't going to cause security problems in the browser.
up
-2
rohankumar dot 1524 at gmail dot com
3 years ago
There is requirement for old projects which are using `mysql_escape_string`, and upgrading the PHP version to 7 and above. Basically this happens in maintenance projects where we don't know how many files the functions are used in application. We can use [mysqli.real-escape-string][1] for the function:

If you have a typical connection file like `conn.php`

$conn = new mysqli($host, $user, $password, $db);
// may be few more lines to handle the $conn
if (!function_exists('mysql_escape_string')) {
function mysql_escape_string($sting){ // if mysql_escape_string not available
return $conn->real_escape_string($string); // escape using the $conn instance
}
}

[1]: https://www.php.net/manual/en/mysqli.real-escape-string.php
up
1
strata_ranger at hotmail dot com
14 years ago
There's an interesting quirk in the example #2 about SQL injection: AND takes priority over OR, so the injected query actually executes as WHERE (user='aidan' AND password='') OR ''='', so instead of returning a database record corresponding to an arbitrary username (in this case 'aidan'), it would actually return ALL database records. In no particular order. So an attacker might be able to log in as any account, but not necessarily with any control over which account it is.

Of course a potential attacker could simply modify their parameters to target specific users of interest:

<?php

// E.g. attacker's values
$_POST['username'] = '';
$_POST['password'] = "' OR user = 'administrator' AND '' = '";

// Malformed query
$query = "SELECT * FROM users WHERE user='$_POST[username]' AND password='$_POST[password]'";

echo
$query;

// The query sent to MySQL would read:
// SELECT * FROM users WHERE user='' AND password='' OR user='administrator' AND ''='';
// which would allow anyone to gain access to the account named 'administrator'

?>
To Top