Question

I am using php 5.4.4 running as UTF-8, and im not sure if I am using htmlspecialchars right.

My strings / vars look like this:

$text = "<p><span class='clx'>By:</span> ".htmlspecialchars($foo)."</span></p>";
echo $text;

Do I have need to use ENT_QUOTES or is that only necessary when I have to echo something

inside eg: href="$foo" or id='$foo' ?

Atm, om only using htmlspecialchars inside closed html tags and not attributes.

Just concatenate the var inside the string within a <p> tag and a </p> tag

Thanks

Was it helpful?

Solution

You should generally use it when taking data from database and inserting it into html elements. This is so that quotes from the data don't close the value quotes and mess up the html.

OTHER TIPS

Short answer: Always.

Long answer: I highly recommend reading OWASP's PHP Top 5 and PHP Security Cheat Sheet

The OWASP Top 5 covers the five most serious and common security vulnerabilities afflicting PHP today:

  • Remote Code Execution
  • Cross-Site Scripting (XSS) [The one htmlspecialchars is trying to prevent]
  • SQL Injection
  • PHP Configuration
  • File System Attacks

It demonstrates common mistakes and solutions and is well worth reading for any PHP developer even considering hosting a live website.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top