Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best practice to set html attribute via PHP?

Tags:

html

php

When doing this job in PHP,one may meet this kind of issue:

<span title="<?php echo $variable;?>">... 

The problem is that if $variable contains double quotes,should change it to \"

And that's not the whole story yet:

<span title='<?php echo $variable;?>'>... 

In this case,we need to change single quotes to \',but leave double quotes as is.

So how can we do it in a general property manner?

like image 600
user198729 Avatar asked Jan 21 '10 13:01

user198729


People also ask

Where should HTML attributes be placed?

Attributes are always specified in the start tag (or opening tag) and usually consists of name/value pairs like name="value" . Attribute values should always be enclosed in quotation marks.

What are the 3 types of attribute in HTML?

HTML attributes are generally classified as required attributes, optional attributes, standard attributes, and event attributes: Usually the required and optional attributes modify specific HTML elements.


1 Answers

You always want to HTML-encode things inside HTML attributes, which you can do with htmlspecialchars:

<span title="<?php echo htmlspecialchars($variable); ?>"> 

You probably want to set the second parameter ($quote_style) to ENT_QUOTES.

The only potential risk is that $variable may already be encoded, so you may want to set the last parameter ($double_encode) to false.

like image 130
Dominic Rodger Avatar answered Oct 03 '22 20:10

Dominic Rodger