views:

59

answers:

1

What is the safest way to accept user inputted programming code in PHP, store it in database and display it back with the HTML pre tag?

I currently convert the input to HTML entities, but I somehow think it wouldn't be that easy...

Any suggestions?

+5  A: 

Programming code is just text; if it's not executed there can't be any harm done.

This means you need to be concerned about:

  • Protecting your database from SQL injection. This can be done by escaping the input string (mysql_real_escape_string()) or using prepared statements.

  • Protecting your users from XSS. This can be done by converting your code to html entities (ie: using htmlspecialchars()), so potentially malicious tags (ie: <script>) get converted to text (eg: &lt;script&gt;).

NullUserException
I know, but my concern is whether it's completely safe (from XSS/SQL-Injection) to use only htmlspecialchars() to sanitize the code before it goes into database?
Ѓоре Саздовски
@Ѓоре If done correctly, yes I *believe* so. I am no security expert, but as long as malicious code can't be executed, you should be fine.
NullUserException
@Ѓоре Саздовски: You don't need to escape the HTML entities when you're putting the code into the database, but you do need to escape the code using a function provided by your database (like `mysql_real_escape_string()` for MySQL) or your site is open to SQL-injection attacks. Using `htmlspecialchars` is not good enough to protect you against SQL-injection attacks (however it will prevent XSS attacks, and should also be applied to the code before it gets embedded in HTML).
Cameron
htmlspecialchars($string, ENT_QUOTES) - correct enough?I'm using prepared statements with CodeIgniter.
Ѓоре Саздовски
@Ѓоре I think that's good enough
NullUserException
Prepared statements will escape the code as before it gets sent to the DB as an SQL statement, so yes, that's fine. I didn't see that you were using them before :-)
Cameron