简体   繁体   中英

For PHP function mysqli_real_escape_string(), what is the purpose of $link?

The PHP documentation for mysqli_real_escape_string notes that a link identifier is necessary to escape a string:

string mysqli_real_escape_string ( mysqli $link , string $escapestr )

What purpose does $link serve? And why is $link necessary in order to escape a string? And how is it that a different valid value for $link could conceivably lead to a different return value for mysqli_real_escape_string ?

That's a good and very logical question. Indeed, why would we need a connection for a trifle string manipulation - adding slashes to certain characters?

All this hassle is about the character set.

$link contains a mysqli connection. And mysqli connection contains the information about current charset. And this information is required to escape the string properly, depends on charset. So indeed the result will be different for some different (though quite odd) character sets.

A different returned value example can be found in this answer .

This is why mysqli_real_escape_string() does no good by itself, but should be always used after setting the proper charset through mysqli::set_charset()

On a side note I must say that this function is rather obsoleted whatsoever. Instead of manual escaping one should use prepared statements (and, given with mysqli this this mechanism is one big WTF, it is hugely recommended to use PDO).

Consult the "edit" further below.

As per the manual:

Note: For those accustomed to using mysql_real_escape_string(), note that the arguments of mysqli_real_escape_string() differ from what mysql_real_escape_string() expects. The link identifier comes first in mysqli_real_escape_string(), whereas the string to be escaped comes first in mysql_real_escape_string().

and from User Contributed Notes:

Note, that if no connection is open, mysqli_real_escape_string() will return an empty string!

The connection is now required in mysqli_* functions that require it.

In the past, certain mysql_ functions such as mysql_real_escape_string() , the connection was assumed already open, but not in mysqli_ .

As per mysql_real_escape_string()

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() had been called with no arguments. If no connection is found or established, an E_WARNING level error is generated.

More on the mysqli_ API:


Edit: After seeing a comment about my not answering the "why", have found the following Q&A on Information Security Stack Exchange which will better explain this:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM