开发者

Html in my database!

开发者 https://www.devze.com 2023-01-21 07:33 出处:网络
I am faced with something I dont know where to start with. I currently have a news section on my website, the news is added into the database.

I am faced with something I dont know where to start with.

I currently have a news section on my website, the news is added into the database. However, it's开发者_如何学运维 very dull and has no formatting!

How can I allow the admin thats adding news to make things bold or underlined and have colour etc. Will it be possible to save this in the database as I usually do.

Sorry if it's a really silly question, but it's something I haven't come across before!

Thanks


Whilst you can put HTML in your database and display it directly without the normal encode step that you would use outputting text into HTML, I wouldn't recommend it unless you absolutely trust everyone that'll be entering content.

I mean trust not just as in security (because anyone who can insert HTML into your page will be able to take over other users' usage of the site via script-injection), but also competence: it only takes one stray unclosed <div> or other similar markup mistake to completely hose the page layout.

One possibility is to vet incoming HTML submissions using a strong HTML tidier and ‘purifier’ to allow only known-safe markup. This is a tricky job, so use an existing library to do it. Alternatively, and perhaps more usably, you can provide a simple markup language of your own. For example *italic*, **bold**, http:​//www.example.com/ -> italic, bold, http://www.example.com/.

There are lots of these little markup languages about. The one Stack Overflow uses, that I'm typing in this box right now, is called Markdown.

(Markdown's not my favourite, primarily because in the usual implementation it also allows HTML content inside the markup itself, which is a bit ugly and causes problems here when people try to talk about tags without putting them in `-quotes. But it's a popular example; there are many more: bbcode, reST, Textile etc...)


Adding CKEditor to a form that the admin can use will allow them to create some funky html. CKEditor is super easy to setup and use. You can save the output from it to the database as you do with your current HTML.


Sure:

INSERT INTO tbl (html_text) values ('<h1>Hello, world.</h1>')

(You should use parameterized queries, of course.)


If they enter the data in as HTML you can store it in the DB as a varchar(max) and you should be alright, as long as it is parsed as HTML when it comes out (ie. in a webpage). Otherwise, if it's parsed as plain-text you'll see all the HTML tags.


You can use any number of rich text editors to provide the functionality to apply formatting to you text. Then you can save that in the DB, just as you would the plain text.

Just make sure to HTML encode your output.

I prefer the CKEditor for my rich text editor. Very robust, mature, and cross platform.

0

精彩评论

暂无评论...
验证码 换一张
取 消