|
Posted by Hilarion on 09/20/05 13:39
> I have a photo album page written in PHP where I pull captions and such from
> an SQL
> database and the result is of course an HTML page.
>
> My problem is with the use of an apostrophe (single quote) and other such
> characters as they break my HTML. I'm also using javascript and it's a
> problem there as well.
>
> How should I store such characters in SQL, or maybe just how should I read
> them out so they can't break my code, yet they show up on the screen fine?
>
> The method I use to insert such characters works without problems. In the
> SQL I get what was intended... e.g. Ginny's Wedding
>
> However when I pull it out I get this: (seemingly correct)
>
> <a href="album.php?albumid=293&frompage=1"><img id="img_two"
> src="data/293/0/cover3.jpg" alt="Ginny's Wedding"
> onMouseOver="switchit('Ginny's Wedding - Jun 11 2005');"
> onMouseOut="clearit();"></a><br>
>
> ...But then my JS broken because the text is in single quotes and another
> extra one breaks it.
Assuming that you really have "Ginny's Wedding" in the database (which
is correct approach) and you retrieve it from database correctly (still
have "Ginny's Wedding", not for example "Ginny\'s Wedding) into variable
called for example $name, then you could do it like this:
<?php
//$ident = 'img_two';
//$name = "Ginny's Wedding";
//$location = 'data/293/0/cover3.jpg';
function js_escape_string( $text )
{
return addcslashes( $text, '\'\\"'."\n\r" );
}
$id = htmlspecialchars( $ident );
$src = htmlspecialchars( $location );
$alt = htmlspecialchars( $name );
$onmouseover = htmlspecialchars( "switchit('" . js_escape_string( $name ) . "');" );
$onmouseout = htmlspecialchars( 'clearit();' );
printf(
'<img id="%s" src="%s" alt="%s" onMouseOver="%s" onMouseOut="%s" />',
$id, $src, $alt, $onmouseover, $onmouseout
);
?>
Function "js_escape_string" is designed to escape strings the way the JavaScript
expects, so they can be placed as part of JavaScript strings. "htmlsiecialchars"
is used to change characters which are special in HTML to their entity representation
(it'll work OK for attribute values enclosed with double quotes, if you want to
use single quotes, then you'll have to use "htmlspecialchars" function optional
parameter to make it also encode single quote char).
Hilarion
PS.: "addslashes" function should not be used in place of "addcslashes" because
it does NOT escape many chars that JavaScript requires to be escaped.
If you'll notice that some character that should be escaped for JS is not
escaped, then add it to the second parameter of "addcslashes" in
"js_escape_string" function (you should escape "<" and ">" chars if the
string is inside <script> tag and may contain text "</script>", but you
do not have to escape those chars if the JavaScript code is in HTML
attribute value).
[Back to original message]
|