views:

24

answers:

1

Hi folks

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.

+3  A: 

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
Excellent, thank you! I've also added an extra bit to the question too... :)
Jack Webb-Heller
@Jack `highlight_string()` won't work because you're inside the `pre` and `code` blocks. They don't support HTML formatting.
Pekka
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 Webb-Heller
@Jack the highlight_string function needs to be the outermost one, as you have it in the example in your question.
Pekka
I really appreciate the help @Pekka, but when I try that this is output: http://cl.ly/5df1ec7621b4d6984686 - again, a mystery '1' afterwards...
Jack Webb-Heller
@Jack Check out http://php.net/highlight_string you need to set the 2nd parameter of highlight_string to true.
Pekka