Using nl2br and mysql_real_escape_string at same time
Whats the correct way to use nl2br in the following way.
I have post data that comes from a text area input
$data = $_POST;
$escaped_data = array();
foreach ($data as $key => $val) {
$escaped_data[$ke开发者_运维百科y] = mysql_real_escape_string($val);
}
$desc = $escaped_data[description];
$desc = nl2br($desc);
Actually, the correct way to use nl2br() is not to use it at all when you store your data - it's when you read from the database and are about to output it to the client. Data should not be formatted when insterted to the database, what if you later on want to create a REST-service and you really needed those newlines instead of a HTML-element?
Generally speaking, if you wish to add a string to your SQL query, you should escape it immediately before adding it to your SQL query.
I assume that you want to escape all your data at the start of your PHP script, so that you will not have to worry about escaping.
Escaping string for SQL queries shouldn't be included there because that's a bad design method:
- What happens when you add the escaped string to an input element of an HTML form? The original client's string will be modified.
- It's an inconvenient or problematic way to use prepared statements with the already escaped data.
I think that the following code should be used:
function init_filter_input($method_array /* $_GET, $_POST, or whatever you wish */ )
{
filter_UTF8($method_array); // for a UTF8 encoded string
filter_HTML($method_array);
}
function filter_UTF8($mixed)
{
return is_array($mixed)
? array_map('filter_UTF8',$mixed)
: iconv('UTF-8','UTF-8//IGNORE',$mixed);
}
function filter_HTML($mixed)
{
return is_array($mixed)
? array_map('filter_HTML',$mixed)
: htmlspecialchars(trim($value),ENT_QUOTES);
}
When you want to add a string to your SQL query, you may decide to use prepared statements, or sprintf:
// sprintf example:
query('SELECT ... WHERE username="%s"', $unescaped_username);
function query($query_str, $params)
{
if (is_array($params))
{
$params = array_map('filter_SQL', $params);
$query_str = vsprintf($queryStr, $params);
}
else
$query_str = sprintf($query_str ,filter_SQL($params));
mysql_query($query_str);
}
精彩评论