views:

118

answers:

4

And I'm talking (especially) forums here - [PHP]code here[/PHP] - style. Some forums escape double quotes or other "dangerous characters" and others don't.

What is the best method? What are you guys using? Can it be done without the fear of code injection?

Edit: Who said anything about reinventing the wheel?

+6  A: 

When PHP echo or print text, it never executes it. That only happens with eval. This means that if you did this:

echo '<?php ... ?>';

it would carry through to the page output and not be parsed or executed.

This means that all you need to do is escape the usual characters (<, >, &, etc.) and you should generally be safe.

Delan Azabani
+3  A: 

Don't reinvent the wheel. I see BBCode in your question. Grab a markdown library and use it instead. SO uses this: http://daringfireball.net/projects/markdown/

stillstanding
+2  A: 
  1. There is no fear of PHP code injection (unless you are doing some unusual things like eval'ing HTML templates) but always a fear of JS code injection, often called XSS. And all danger coming only from possible JS code.
  2. Thus, there is no special treatment for the PHP code, shown on a HTML page. Just treat it as any other data. < > brackets usually being escaped, for obvious reason.
  3. Don't reinvent the wheel. PHP has it's highlight_string function for this
Col. Shrapnel
A: 

If you see escaped quotes on some page, that's most likely because their script escaped them twice (for example magic_quotes did it once, then mysql_query() again). When data sanitisation is done properly, you should not see escape characters in output.

Mchl