Search code examples
phphtmlhtmlspecialchars

Should I use htmlspecialchars inside <a> tag


The title says it all.

Should I include htmlspecialchars(); function inside <a> tag?

Thanks


Solution

  • htmlspecialchars is a function to escape certain characters which have a special meaning in HTML. For example, if you wanted to embed a value which contains quotes inside an HTML attribute:

    <a title="Simon says "Hello World"">
    

    This obviously breaks the HTML syntax. You need to apply the escaping function to the value Simon says "Hello World" to arrive at:

    <a title="Simon says &quot;Hello World&quot;">
    

    This is now correct HTML syntax.

    The same goes for values containing < or > in regular text, because those can obviously be interpreted as HTML tags. Read The Great Escapism (Or: What You Need To Know To Work With Text Within Text) for more on the topic.

    You need to do this the same way for all HTML tags and values.

    printf('<a href="%s" title="%s">%s</a>',
           htmlspecialchars($url),
           htmlspecialchars($title),
           htmlspecialchars($content));
    

    URLs have their own escaping rules, you may have to URL encode values you put into a URL before you put it into HTML:

    $url = sprintf('/foo/%s', urlencode($bar));
    printf('<a href="%s">...</a>', htmlspecialchars($url));