0

I'm learning about making my site more secure and am using mysqli's escape function to sanitize input going into SQL queries and am using htmlspecialchars() on input coming from the database (or get/post requests) echoing out onto the page.

But, any text coming from the database to display to the user looks bad because certain characters are escaped with slashes and it shows <br /> or \r\n instead of doing a line break. I can strip the slashes, of course, but shouldn't the mysqli string escape function change the escaped characters back once it is put into the database?

Am I not supposed to use htmlspecialchars to sanitize output being displayed to the user? Or should this not be happening (in which case there must be something weird going on to the data going in)?

I still want line breaks so I'm having to do a string replace. I made the function below as a replacement for just htmlspecialchars(). But I'm not seeing anything about having to do this online anywhere so I'm afraid maybe I'm doing something wrong. :-/

function display($data) {

$new = str_replace('\r\n',"<br />",$data);
$new = str_replace('\n',"<br />",$new);
$new = str_replace('\r',"<br />",$new);

$new = stripslashes($new);
$newer = htmlspecialchars($new);
    $search  = array('&lt;b&gt;', '&lt;/b&gt;', '&lt;i&gt;', '&lt;/i&gt;', '&lt;u&gt;', '&lt;/u&gt;', '\r\n', '&lt;br /&gt;');
    $replace = array('<b>', '</b>', '<i>', '</i>', '<u>', '</u>', '<br />', '<br />');

  $newest = str_replace($search, $replace, $newer);

  return $newest;
}

Here's what I'm using to sanitize the input going into the database:

function escape($data) {
    global $conn;
    connect();
    $data = stripslashes($data);
    $data = $conn->real_escape_string($data);
    $conn->close();
    $data = str_replace(chr(0), '', $data);
    return $data;
}

function sanitize($data) {
  $data = trim($data);
  $data = strip_tags($data);
  $data = escape($data);
  $data = htmlspecialchars($data);
  return $data;
}
thinkofacard
  • 491
  • 1
  • 6
  • 19
  • 1
    One wishy-washy function for sanitzing *every* string alike isn't going to work out. [What are the best PHP input sanitizing functions?](http://stackoverflow.com/q/3126072) -- Use html escaping for output. Don't double-escape it unilaterally, only to decode it partially later/sometimes. – mario Jul 10 '15 at 17:46
  • This is just for blog posts and comments written by the user. I have separate functions for id numbers and usernames, – thinkofacard Jul 10 '15 at 17:53
  • also I'm using html purifier instead of htmlspecialchars now but that's not reflected in the above function. Once I get this issue solved I'll substitute it into this function. – thinkofacard Jul 10 '15 at 17:55

0 Answers0