Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks,

Please help me with the question below:

I've form to get text input from the user. The input is then saved into an sql database (MySQL to be exact).

If the input contains a literal double quote " or literal angle brackets, do I save these into the database as is? Or do I need to convert them to their html equivalents (i.e. ambersandquote; for a double quote) first before saving?

I'll need to display the saved text on a web page later.

What is the procedure like? Convert before saving into the database or save everything as is, then convert to html-safe equivalents when outputting to a web page.

I hope my question is clear.

Thanks!

Replies are listed 'Best First'.
Re: Format to save and display
by Happy-the-monk (Canon) on Jun 08, 2004 at 12:52 UTC

    Convert before saving into the database or save everything as is, then convert to html-safe equivalents when outputting to a web page.

    That's essentially up to your requirements. If you will need the HTML version most of the time, it might be wise to safe it that way.

    To quote your values from being misunderstood by the database: DBI.pm (if you're using that) has a   quote()   method/function that does the escaping of metacharacters for you the way your target database expects it (i.e. not HTML).

    That seems to be done automatically if you are useing placeholders in your sql syntax, otherwise it's up to you to do it. Give it a try.

    Update:
    Convert to HTML code - which may or may be not safe, depending on what you include in the conversion.
    Essentially double (") and single (') quotes could be seen as a threat to the DB. HTML encoding should have taken care of the former, making it ", but might not take care of the latter.
    You might still need DBI::quote().

    Update 2:
    Zaxo adds: Be careful, semicolons are particularly unsafe with SQL. No time to relax on placeholders or quoting :-)

    Cheers, Sören

      >That's essentially up to your requirements. If you will need the HTML version most of the time, it might be wise to safe it that way.

      You mean convert to safe-html code, then save into the database?
Re: Format to save and display
by pelagic (Priest) on Jun 08, 2004 at 12:47 UTC
    As a general rule for my work I always try to safe things as native as possible. So I can prepare the data specifically to the later needs, e.g. display it in html a.s.o.

    pelagic
      I'm worried about security.

      What if the text contains evil code? For example, code that can be executed with '<script>code here</script>'
Re: Format to save and display
by Roger (Parson) on Jun 08, 2004 at 12:57 UTC
    A method I sometime use is to save the text input as it is to an external file, of name perhaps a sequence number maintained in the database. And then simply store the path to the text file in the database instead. Nice and simple.