0

I have this function that takes some user-submitted HTML code from the database:

function Code($code)
{
    return "<pre><code>".nl2br(htmlspecialchars($code))."</code></pre>";
}

I'll just be calling it like echo code($query->row('html'));. I know my question lacks 'depth', but is this the best way to do it? Or could the outputted formatting be parsed (e.g. Javascript injections), or not output correctly on some machines, etc.?

Thanks!

Jack

EDIT: I have a new (related) question: I would like to highlight the string using highlight_string(). However, I cannot make it work properly. I think I understand why but am not too sure how I can rectify this.

function Code($code)
{
    return "<pre><code>".highlight_string(nl2br(htmlspecialchars($code)))."</code></pre>";
}

As you can see from that I'm using highlight_string() on it all. however, the output isn't highlighted at all, instead it is output as character entities (&lt;, '>' etc). If I reshuffle the function ordering to something like:

return "<pre><code>".nl2br(htmlspecialchars(highlight_string($code)))."</code></pre>";

I find that the character entities aren't output, but the string still isn't highlighted. To clarify, I have no CSS formatting that would affect the text colour applied either. Also, I've checked my PHP settings and there are definitely highlighting colours specified in there.

Jack
  • 9,615
  • 18
  • 72
  • 112

1 Answers1

3

Nope, that's fine. htmlspecialchars() will turn any HTML control character into its entity equivalent (< => &lt; etc.), there is no way of injecting anything there.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • Excellent, thank you! I've also added an extra bit to the question too... :) – Jack Aug 10 '10 at 11:42
  • @Jack `highlight_string()` won't work because you're inside the `pre` and `code` blocks. They don't support HTML formatting. – Pekka Aug 10 '10 at 11:44
  • I changed the Code() function to read this: `return "".nl2br(htmlspecialchars(highlight_string($code)))."";` - sadly, it still doesn't work. I've also tried 'shuffling' the depth of the `highlight_string()` function (e.g. putting it at the front), but no luck. There are also unusual '1's being output, see screenshot: http://cl.ly/603f491d7402e06125be - they're definitely not in the Database data. – Jack Aug 10 '10 at 11:48
  • @Jack the highlight_string function needs to be the outermost one, as you have it in the example in your question. – Pekka Aug 10 '10 at 11:52
  • I really appreciate the help @Pekka, but when I try that this is output: http://cl.ly/5df1ec7621b4d6984686 - again, a mystery '1' afterwards... – Jack Aug 10 '10 at 11:57
  • @Jack Check out http://php.net/highlight_string you need to set the 2nd parameter of highlight_string to true. – Pekka Aug 10 '10 at 11:58