Storing HTML in MySQL

I store HTML and text data in my database table in its raw form - however, I have a slight problem in getting it to output correctly. Here are some examples of data stored in the AS IS table:

<p>Professional Freelance PHP & MySQL developer based in Manchester. <br />Providing an unbeatable service at a competitive price.</p> 

To display this data, follow these steps:

 echo $row['details']; 

And this correctly outputs the data, however, when I check the W3C validator, it says:

 character "&" is the first character of a delimiter but occurred as data 

So I tried using htmlemtities and htmlspecialchars , but it just causes the HMTL tags to be displayed on the page.

What is the right way to do this?

+4
source share
4 answers

Use &amp; instead of & .

+10
source

What you want to do is use the php htmlentities() function ...
It converts your input into html objects, and then when it is output, it will be interpreted as HTML and output as a result of this HTML ...
For instance:

 $mything = "<b>BOLD & BOLD</b>"; //normally would throw an error if not converted... //lets convert!! $mynewthing = htmlentities($mything); 

Now just paste $mynewthing into your database !!

+5
source

htmlentities is basically a superset of htmlspecialchars , and htmlspecialchars also replaces < and > .

Actually, you are trying to fix the wrong HTML code, and I think this requires an ad-hoc solution:

 $row['details'] = preg_replace("/&(?![#0-9a-z]+;)/i", "&amp;", $row['details']); 

This is not an ideal solution, as it will fail for strings such as: someone&son; (with final ; ), but at least it wonโ€™t break existing HTML objects.

However, if you have authority to manage data storage, make sure that the HTML code stored in the database is correct.

+2
source

In my projects I use XSLT Parser, so I had to change &nbsp; on &#160; (eg,). But this is the security method I found ...

here is my code

 $html = trim(addslashes(htmlspecialchars( html_entity_decode($_POST['html'], ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8' ))); 

And when you read from the database, don't forget to use stripslashes ();

 $html = stripslashes($mysq_row['html']); 
0
source

Source: https://habr.com/ru/post/1486432/


All Articles