Escape for mysql php

mysql_real_escape_string

Данное расширение устарело, начиная с версии PHP 5.5.0, и будет удалено в будущем. Используйте вместо него MySQLi или PDO_MySQL. Смотрите также инструкцию MySQL: выбор API и соответствующий FAQ для получения более подробной информации. Альтернативы для данной функции:

Описание

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

Экранирует специальные символы в unescaped_string , принимая во внимание кодировку соединения, таким образом, что результат можно безопасно использовать в SQL-запросе в функции mysql_query() . Если вставляются бинарные данные, то к ним так же необходимо применять эту функцию.

mysql_real_escape_string() вызывает библиотечную функцию MySQL mysql_real_escape_string, которая добавляет обратную косую черту к следующим символам: \x00, \n, \r, \, , « и \x1a.

Эта функция должна всегда (за несколькими исключениями) использоваться для того, чтобы обезопасить данные, вставляемые в запрос перед отправкой его в MySQL.

Безопасность: кодировка символов по умолчанию

Кодировка символов должна устанавливаться как на сервере, так и с помощью функции mysql_set_charset() , чтобы влиять на поведение mysql_real_escape_string() . Подробнее описано в разделе кодировка символов.

Список параметров

Соединение MySQL. Если идентификатор соединения не был указан, используется последнее соединение, открытое mysql_connect() . Если такое соединение не было найдено, функция попытается создать таковое, как если бы mysql_connect() была вызвана без параметров. Если соединение не было найдено и не смогло быть создано, генерируется ошибка уровня E_WARNING .

Возвращаемые значения

Возвращает строку, в которой экранированы все необходимые символы, или FALSE в случае ошибки.

Примеры

Пример #1 Простой пример использования mysql_real_escape_string()

// Соединение
$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-инъекции

// Мы не никак проверили переменную $_POST[‘password’],
// а она может содержать совсем не то, что мы ожидали. Например:
$_POST [ ‘username’ ] = ‘aidan’ ;
$_POST [ ‘password’ ] = «‘ OR »='» ;

// посылаем запрос, чтобы проверить имя и пароль пользователя
$query = «SELECT * FROM users WHERE user=’ < $_POST [ 'username' ]>‘ AND password=’ < $_POST [ 'password' ]>‘» ;
mysql_query ( $query );

// посмотрим, какой запрос будет отправлен в MySQL:
echo $query ;
?>

Запрос, который будет отправлен в MySQL:

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

Это позволит кому угодно войти в систему без пароля.

Читайте также:  Php encode file to utf 8

Примечания

Замечание:

Функцию mysql_real_escape_string() можно использовать только после того, как установлено соединение с MySQL. В противном случае возникнет ошибка уровня E_WARNING , а функция возвратит FALSE . Если link_identifier не указан, используется последнее открытое соединение.

Замечание:

Если magic_quotes_gpc включены, то сначала данные следует обработать функцией stripslashes() . Если данную функцию применить к уже проэкранированным данным, то данные будут проэкранированы дважды.

Замечание:

Если не пользоваться этой функцией, то запрос становится уязвимым для взлома с помощью SQL-инъекций.

Замечание: mysql_real_escape_string() не экранирует символы % и _. Эти знаки являются масками групп символов в операторах MySQL LIKE, GRANT и REVOKE.

Смотрите также

  • mysql_set_charset() — Устанавливает кодировку клиента
  • mysql_client_encoding() — Возвращает кодировку соединения
  • addslashes() — Экранирует строку с помощью слешей
  • stripslashes() — Удаляет экранирование символов
  • Директива magic_quotes_gpc
  • Директива magic_quotes_runtime

Источник

mysql_escape_string

This function was deprecated in PHP 4.3.0, and it and the entire original MySQL extension was removed in PHP 7.0.0. Instead, use either the actively developed MySQLi or PDO_MySQL extensions. See also the MySQL: choosing an API guide. Alternatives to this function include:

Description

This function will escape the unescaped_string , so that it is safe to place it in a mysql_query() . This function is deprecated.

This function is identical to mysql_real_escape_string() except that mysql_real_escape_string() takes a connection handler and escapes the string according to the current character set. mysql_escape_string() does not take a connection argument and does not respect the current charset setting.

Parameters

The string that is to be escaped.

Return Values

Returns the escaped string.

Examples

Example #1 mysql_escape_string() example

$item = «Zak’s Laptop» ;
$escaped_item = mysql_escape_string ( $item );
printf ( «Escaped string: %s\n» , $escaped_item );
?>

The above example will output:

Escaped string: Zak\'s Laptop

Notes

Note:

mysql_escape_string() does not escape % and _ .

See Also

User Contributed Notes 1 note

You can use this function safely with your MySQL database queries if and only if you are sure that your database connection is using ASCII, UTF-8, or ISO-8859-* and that the backslash is your database’s escape character. If you’re not sure, then use mysqli_real_escape_string instead. This function is not safe to use on databases with multi-byte character sets.

The only benefit of this function is that it does not require a database connection.

  • MySQL Functions
    • mysql_​affected_​rows
    • mysql_​client_​encoding
    • mysql_​close
    • mysql_​connect
    • mysql_​create_​db
    • mysql_​data_​seek
    • mysql_​db_​name
    • mysql_​db_​query
    • mysql_​drop_​db
    • mysql_​errno
    • mysql_​error
    • mysql_​escape_​string
    • mysql_​fetch_​array
    • mysql_​fetch_​assoc
    • mysql_​fetch_​field
    • mysql_​fetch_​lengths
    • mysql_​fetch_​object
    • mysql_​fetch_​row
    • mysql_​field_​flags
    • mysql_​field_​len
    • mysql_​field_​name
    • mysql_​field_​seek
    • mysql_​field_​table
    • mysql_​field_​type
    • mysql_​free_​result
    • mysql_​get_​client_​info
    • mysql_​get_​host_​info
    • mysql_​get_​proto_​info
    • mysql_​get_​server_​info
    • mysql_​info
    • mysql_​insert_​id
    • mysql_​list_​dbs
    • mysql_​list_​fields
    • mysql_​list_​processes
    • mysql_​list_​tables
    • mysql_​num_​fields
    • mysql_​num_​rows
    • mysql_​pconnect
    • mysql_​ping
    • mysql_​query
    • mysql_​real_​escape_​string
    • mysql_​result
    • mysql_​select_​db
    • mysql_​set_​charset
    • mysql_​stat
    • mysql_​tablename
    • mysql_​thread_​id
    • mysql_​unbuffered_​query

    Источник

    mysqli_real_escape_string

    This function is used to create a legal SQL string that you can use in an SQL statement. The given string is encoded to produce an escaped SQL string, taking into account the current character set of the connection.

    Security: the default character set

    The character set must be set either at the server level, or with the API function mysqli_set_charset() for it to affect mysqli_real_escape_string() . See the concepts section on character sets for more information.

    Parameters

    Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

    Characters encoded are NUL (ASCII 0), \n, \r, \, ‘, «, and Control-Z .

    Return Values

    Returns an escaped string.

    Examples

    Example #1 mysqli::real_escape_string() example

    mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
    $mysqli = new mysqli ( «localhost» , «my_user» , «my_password» , «world» );

    /* this query with escaped $city will work */
    $query = sprintf ( «SELECT CountryCode FROM City WHERE name=’%s'» ,
    $mysqli -> real_escape_string ( $city ));
    $result = $mysqli -> query ( $query );
    printf ( «Select returned %d rows.\n» , $result -> num_rows );

    /* this query will fail, because we didn’t escape $city */
    $query = sprintf ( «SELECT CountryCode FROM City WHERE name=’%s'» , $city );
    $result = $mysqli -> query ( $query );

    mysqli_report ( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
    $mysqli = mysqli_connect ( «localhost» , «my_user» , «my_password» , «world» );

    /* this query with escaped $city will work */
    $query = sprintf ( «SELECT CountryCode FROM City WHERE name=’%s'» ,
    mysqli_real_escape_string ( $mysqli , $city ));
    $result = mysqli_query ( $mysqli , $query );
    printf ( «Select returned %d rows.\n» , mysqli_num_rows ( $result ));

    /* this query will fail, because we didn’t escape $city */
    $query = sprintf ( «SELECT CountryCode FROM City WHERE name=’%s'» , $city );
    $result = mysqli_query ( $mysqli , $query );

    The above examples will output something similar to:

    Select returned 1 rows. Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's-Hertogenbosch'' at line 1 in.

    See Also

    User Contributed Notes 7 notes

    You can avoid all character escaping issues (on the PHP side) if you use prepare() and bind_param(), as an alternative to placing arbitrary string values in SQL statements. This works because bound parameter values are NOT passed via the SQL statement syntax.

    Note that this function will NOT escape _ (underscore) and % (percent) signs, which have special meanings in LIKE clauses.

    As far as I know there is no function to do this, so you have to escape them yourself by adding a backslash in front of them.

    Presenting several UTF-8 / Multibyte-aware escape functions.

    These functions represent alternatives to mysqli::real_escape_string, as long as your DB connection and Multibyte extension are using the same character set (UTF-8), they will produce the same results by escaping the same characters as mysqli::real_escape_string.

    This is based on research I did for my SQL Query Builder class:
    https://github.com/twister-php/sql

    /**
    * Returns a string with backslashes before characters that need to be escaped.
    * As required by MySQL and suitable for multi-byte character sets
    * Characters encoded are NUL (ASCII 0), \n, \r, \, ‘, «, and ctrl-Z.
    *
    * @param string $string String to add slashes to
    * @return $string with `\` prepended to reserved characters
    *
    * @author Trevor Herselman
    */
    if ( function_exists ( ‘mb_ereg_replace’ ))
    function mb_escape ( string $string )
    return mb_ereg_replace ( ‘[\x00\x0A\x0D\x1A\x22\x27\x5C]’ , ‘\\\0’ , $string );
    >
    > else function mb_escape ( string $string )
    return preg_replace ( ‘~[\x00\x0A\x0D\x1A\x22\x27\x5C]~u’ , ‘\\\$0’ , $string );
    >
    >

    ?>

    Characters escaped are (the same as mysqli::real_escape_string):

    00 = \0 (NUL)
    0A = \n
    0D = \r
    1A = ctl-Z
    22 default»>

    /**
    * Returns a string with backslashes before characters that need to be escaped.
    * As required by MySQL and suitable for multi-byte character sets
    * Characters encoded are NUL (ASCII 0), \n, \r, \, ‘, «, and ctrl-Z.
    * In addition, the special control characters % and _ are also escaped,
    * suitable for all statements, but especially suitable for `LIKE`.
    *
    * @param string $string String to add slashes to
    * @return $string with `\` prepended to reserved characters
    *
    * @author Trevor Herselman
    */
    if ( function_exists ( ‘mb_ereg_replace’ ))
    function mb_escape ( string $string )
    return mb_ereg_replace ( ‘[\x00\x0A\x0D\x1A\x22\x25\x27\x5C\x5F]’ , ‘\\\0’ , $string );
    >
    > else function mb_escape ( string $string )
    return preg_replace ( ‘~[\x00\x0A\x0D\x1A\x22\x25\x27\x5C\x5F]~u’ , ‘\\\$0’ , $string );
    >
    >

    ?>

    Additional characters escaped:

    The original MySQL `utf8` character-set (for tables and fields) only supports 3-byte sequences.
    4-byte characters are not common, but I’ve had queries fail to execute on 4-byte UTF-8 characters, so you should be using `utf8mb4` wherever possible.

    However, if you still want to use `utf8`, you can use the following function to replace all 4-byte sequences.

    Источник

Оцените статью