tags:

views:

134

answers:

3

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[$key] = mysql_real_escape_string($val);
  }
  $desc = $escaped_data[description];
  $desc = nl2br($desc);
+1  A: 

As far as i am concerned, i think there is nothing wrong with that code, mysql_real_escape_sting and n2br can be used that way because they perform a different task.

Sarfraz
Not true, please see: http://php.net/manual/en/function.mysql-real-escape-string.php
Dor
+5  A: 

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?

Björn
This can be solved using two different columns in the database: one for the formatted string, the other for the original one.
Dor
Or you just keep the one column unformatted and skips overhead data...
Björn
+1... but PHP apps are _supposed_ to be an inextricable mash of SQL, PHP and HTML aren't they?
Ben James
@Ben James: yes, mostly, but that depends on the application.
Dor
A: 

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:

  1. What happens when you add the escaped string to an input element of an HTML form? The original client's string will be modified.
  2. 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);
}
Dor