PHP: mysql_real_escape_string - Manual in Deutsh
PHP: mysql_real_escape_string - Manual in French
PHP: mysql_real_escape_string - Manual in Polish

You Are At PHP: mysql_real_escape_string - Manual Area


recent searches:
include functions , variable functions , post functions...




If you are new to PHP or just need to refresh your skills, this is the place to start. This series of tutorials will give you the basic knowledge you will need to create a simple PHP website.

PHP is a reflective programming language originally designed for producing dynamic web pages.[1] PHP is used mainly in server-side scripting, but can be used from a command line interface or in standalone graphical applications. Textual User Interfaces can also be created using ncurses.

PHP Manual
PrevNext

mysql_real_escape_string

(PHP 4 >= 4.3.0, PHP 5)

mysql_real_escape_string -- Escapes special characters in a string for use in a SQL statement

Description

string mysql_real_escape_string ( string unescaped_string [, resource link_identifier] )

Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used.

mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.

This function must always (with few exceptions) be used to make data safe before sending a query to MySQL.

Parameters

unescaped_string

The string that is to be escaped.

link_identifier

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If by chance no connection is found or established, an E_WARNING level warning is generated.

Return Values

Returns the escaped string, or FALSE on error.

Examples

Example 1. Simple mysql_real_escape_string() example

<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    OR die(
mysql_error());

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

Example 2. An example SQL Injection Attack

<?php
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);

// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";

// This means the query sent to MySQL would be:
echo $query;
?>

The query sent to MySQL:

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

This would allow anyone to log in without a valid password.

Example 3. A "Best Practice" query

Using mysql_real_escape_string() around each variable prevents SQL Injection. This example demonstrates the "best practice" method for querying a database, independent of the Magic Quotes setting.

<?php

if (isset($_POST['product_name']) && isset($_POST['product_description']) && isset($_POST['user_id'])) {
    
// Connect

    
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password');

    if(!
is_resource($link)) {

        echo
"Failed to connect to the server\n";
        
// ... log the error properly

    
} else {
        
        
// Reverse magic_quotes_gpc effects on those vars if ON.

        
if(get_magic_quotes_gpc()) {
            
$product_name        = stripslashes($_POST['product_name']);
            
$product_description = stripslashes($_POST['product_description']);
        } else {
            
$product_name        = $_POST['product_name'];
            
$product_description = $_POST['product_description'];
        }

        
// Make a safe query
        
$query = sprintf("INSERT INTO products (`name`, `description`, `user_id`) VALUES ('%s', '%s', '%d')",
                    
mysql_real_escape_string($product_name, $link),
                    
mysql_real_escape_string($product_description, $link),
                    
$_POST['user_id']);

        
mysql_query($query, $link);

        if (
mysql_affected_rows($link) > 0) {
            echo
"Product inserted\n";
        }
    }
} else {
    echo
"Fill the form properly\n";
}
?>

The query will now execute correctly, and SQL Injection attacks will not work.

Notes

Note: A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used.

Note: If magic_quotes_gpc is enabled, first apply stripslashes() to the data. Using this function on data which has already been escaped will escape the data twice.

Note: If this function is not used to escape data, the query is vulnerable to SQL Injection Attacks.

Note: mysql_real_escape_string() does not escape % and _. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE.

See Also

mysql_client_encoding()
addslashes()
stripslashes()
The magic_quotes_gpc directive
The magic_quotes_runtime directive

Jak ograniczyć jedzenie słodyczy Jak ograniczyć jedzenie słodyczy
6
www.finansowo.podejrzliwy.kalisz.pl
Prezenty
tanie holowanie Rzeszów

Another Useful functions:


ref.pdo-mysql | ref.pdo-mysql.connection | ref.mysqli | ref.mysql | function.mysqli-warning-count | function.mysqli-use-result | function.mysqli-thread-safe | function.mysqli-thread-id | function.mysqli-store-result | function.mysqli-stmt-store-result | function.mysqli-stmt-sqlstate | function.mysqli-stmt-send-long-data | function.mysqli-stmt-result-metadata | function.mysqli-stmt-reset | function.mysqli-stmt-prepare | function.mysqli-stmt-param-count | function.mysqli-stmt-num-rows | function.mysqli-stmt-insert-id | function.mysqli-stmt-init | function.mysqli-stmt-get-warnings | function.mysqli-stmt-free-result | function.mysqli-stmt-field-count | function.mysqli-stmt-fetch | function.mysqli-stmt-execute | function.mysqli-stmt-error | function.mysqli-stmt-errno | function.mysqli-stmt-data-seek | function.mysqli-stmt-close | function.mysqli-stmt-bind-result | function.mysqli-stmt-bind-param | function.mysqli-stmt-attr-set | function.mysqli-stmt-attr-get | function.mysqli-stmt-affected-rows | function.mysqli-stat | function.mysqli-ssl-set | function.mysqli-sqlstate | function.mysqli-slave-query | function.mysqli-set-opt | function.mysqli-set-local-infile-handler | function.mysqli-set-local-infile-default | function.mysqli-set-charset | function.mysqli-server-init | function.mysqli-server-end | function.mysqli-send-query | function.mysqli-send-long-data | function.mysqli-select-db | function.mysqli-rpl-query-type | function.mysqli-rpl-probe | function.mysqli-rpl-parse-enabled | function.mysqli-rollback | function.mysqli-report | function.mysqli-real-query | function.mysqli-real-escape-string | function.mysqli-real-connect | function.mysqli-query | function.mysqli-prepare | function.mysqli-ping | function.mysqli-param-count | function.mysqli-options | function.mysqli-num-rows | function.mysqli-num-fields | function.mysqli-next-result | function.mysqli-multi-query | function.mysqli-more-results | function.mysqli-master-query | function.mysqli-kill | function.mysqli-insert-id | function.mysqli-init | function.mysqli-info | function.mysqli-get-warnings | function.mysqli-get-server-version | function.mysqli-get-server-info | function.mysqli-get-proto-info | function.mysqli-get-metadata | function.mysqli-get-host-info | function.mysqli-get-client-version | function.mysqli-get-client-info | function.mysqli-get-charset | function.mysqli-free-result | function.mysqli-field-tell | function.mysqli-field-seek | function.mysqli-field-count | function.mysqli-fetch | function.mysqli-fetch-row | function.mysqli-fetch-object | function.mysqli-fetch-lengths | function.mysqli-fetch-fields | function.mysqli-fetch-field | function.mysqli-fetch-field-direct | function.mysqli-fetch-assoc | function.mysqli-fetch-array | function.mysqli-execute | function.mysqli-escape-string | function.mysqli-error | function.mysqli-errno | function.mysqli-enable-rpl-parse | function.mysqli-enable-reads-from-master | function.mysqli-embedded-server-start | function.mysqli-embedded-server-end | function.mysqli-dump-debug-info | function.mysqli-disable-rpl-parse | function.mysqli-disable-reads-from-master | function.mysqli-debug | function.mysqli-data-seek | function.mysqli-connect | function.mysqli-connect-error | function.mysqli-connect-errno | function.mysqli-commit | function.mysqli-close | function.mysqli-client-encoding | function.mysqli-character-set-name | function.mysqli-change-user | function.mysqli-bind-result | function.mysqli-bind-param | function.mysqli-autocommit | function.mysqli-affected-rows | function.mysql-unbuffered-query | function.mysql-thread-id | function.mysql-tablename | function.mysql-stat | function.mysql-select-db | function.mysql-result | function.mysql-real-escape-string | function.mysql-query | function.mysql-ping | function.mysql-pconnect | function.mysql-num-rows | function.mysql-num-fields | function.mysql-list-tables | function.mysql-list-processes | function.mysql-list-fields | function.mysql-list-dbs | function.mysql-insert-id | function.mysql-info | function.mysql-get-server-info | function.mysql-get-proto-info | function.mysql-get-host-info | function.mysql-get-client-info | function.mysql-free-result | function.mysql-field-type | function.mysql-field-table | function.mysql-field-seek | function.mysql-field-name | function.mysql-field-len | function.mysql-field-flags | function.mysql-fetch-row | function.mysql-fetch-object | function.mysql-fetch-lengths | function.mysql-fetch-field | function.mysql-fetch-assoc | function.mysql-fetch-array | function.mysql-escape-string | function.mysql-error | function.mysql-errno | function.mysql-drop-db | function.mysql-db-query | function.mysql-db-name | function.mysql-data-seek | function.mysql-create-db | function.mysql-connect | function.mysql-close | function.mysql-client-encoding | function.mysql-change-user | function.mysql-affected-rows |


PHP is a widely-used general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. If you are new to PHP and want to get some idea of how it works, try the introductory tutorial. After that, check out the online manual, and the example archive sites and some of the other resources available in the links section.