I'm trying to include a string variable as the title to an anchor tag, so when the user hovers over the link, they see the text. The text may or may not include single or double quotes and comes from a mysql table column.
Here is the code:
echo '<a title="'.$classRow['Description'].'">'.$classRow['LongName'].'</a>';
The above code works correctly if $classRow['Description']
is:
In this class, we'll watch a movie.
But the title is truncated after the word 'movie ' if $classRow['Description']
is:
In this class, we'll watch the movie "Life of Pi."
I tried using addslashes($classRow['Description']) but that just displays the slash; the text is still truncated once it reaches the double quote.
This should do it,
$classRow['Description'] = 'In this class, we\'ll watch the movie "Life of Pi."';
echo '<a title="'.htmlspecialchars($classRow['Description'], ENT_QUOTES) .'">' .$classRow['LongName'].'</a>';
PHP Demo: http://sandbox.onlinephpfunctions.com/code/dadb94a797a74cc7fd8c078ca49d8840ddaeb0b3
Function page: http://php.net/manual/en/function.htmlspecialchars.php
Also note the behavior you are experiencing isn't the data being truncated the "
in your string is closing the attribute the rest of the string is then being read as attributes.
Note a malicious user could alter elements in this same way so when outputting user provided input you should use this function as well.