user1294021
user1294021

Reputation: 322

HTML Decoding within textarea

I am having trouble with a site administration tool I built, It allows me to edit articles for my website. I am using google-code-prettify as my articles are on C++ programming, I then use the <pre class="prettyprint"> </pre> tags to specify I am about to start writing C++ code. The problem is that when I write say,

#include <iostream>

And then insert this into my mySQL database, it will properly add insert the text with the <> but when I request the info and display it in a article viewing page. It will break the page as HTML thinks I am trying to add an HTML tag. So when using the &lt; &gt; tags it will properly add these to my database and the article viewer page will properly read the

#include <iostream>

But if I go want to edit the article, it will read the &lt;&gt; as <>. Which on another insert will bring me back to the original problem of inserting the <> into the database and having them not in my viewer. How can I stop HTML from changing &lt;&gt; into the <>, but only if it is inside <pre class"prettyprint"></pre> within my textarea. I have got it working where it will convert everything in the text area using jquery.

$("#contbox").each(
  function () {
    $(this).text($(this).html()).html();
 }
);

Where #contbox is the id of my textarea, however I cannot figure out how to limit this to only within the pre tags,

Thanks in advance

Upvotes: 2

Views: 1032

Answers (1)

Jason
Jason

Reputation: 1784

Best practice is to store the file as unencoded strings and only encode when it is time to display. The biggest reason for this is the same data may be displayed/used in multiple places that require different encoding (or none at all). If your website allows a user to enter HTML formatted text, you should store it in the database exactly as entered and when it comes time to display it to the end user call the appropriate encoding.

You need to call the appropriate encoding on the server side. This would prevent malicious code from being executed before your javascript can run and encode the data and it also means that your user would still see valid text if they have javascript disabled.

Upvotes: 1

Related Questions