-1

Hi I am implementing a comment system . When showing my comments and articles in my view again , i want to use htmlspecialchars but i want my hypelinks can be clicked .

Example Comment :

My favourite web site is < www.facebook.com >.

Then i the backend i change this : to

My favourite web site is < <a href="www.facebook.com">www.facebook.com</a> >

and save in the database .

now i am showing this comment in view , if i used echo htmlspecialchars($message) the message will be

My favourite web site is < <a href="www.facebook.com">www.facebook.com</a> >

But i want my link to be a hyperlink , but other part should be using htmlspecailchars

I can check for the hypelink in the string and do some complex logic to do add htmlspecailchars only to other parts . I have two questions .

  1. Is it good practice to add a hyperlink to the database or it should be created when viewing data ?

2.What is a better way to use htmlspecialchars for only strings other than hyperlinks .

like exclude only the <a> tags

in htmlentities function i saw optional character-set parameter A string that specifies which character-set to use . is there anything like exclude character set .

Thanks in advance

Kanishka Panamaldeniya
  • 17,302
  • 31
  • 123
  • 193

1 Answers1

0

Your database should store raw data (sanitized for sure but not transformed). Thus the transformation link → link should happen just before view time, not before DB storage.

As for the why you should store raw data: Nothing tells you that one day you won't use your data in other things than HTML, thus the formatting would have to be cleaned up for this other use.

To sum up:

  • You should store raw (sanitized for SQL)
  • Retrieve raw
  • Sanitize HTML
  • Transform links
  • Display
Benoît Latinier
  • 2,062
  • 2
  • 24
  • 36