I need help escaping string parameters for a javascript function using PHP -
i dynamically creating anchor calls javascript function. works 1 string parameter not two. believe not escaping quotes around parameters correctly. in search answer came across following
onclick="alert('<?echo $row['username']?>')"
and next 1 found left me baffled
echo('<button type="button" id="button'.$ctr.'"onclick="showmapsinfo(\''.str_replace("'", "\\'", $maps_name).'\', \''.str_replace("'", "\\'", $ctr).'\');"><img src="img/maps_logo.gif"></button><br/>');
if please
explain why single quotes around username not have escaped?
where there "dummies" write on escaping characters try decipher second example.
let's examine first example
onclick="alert('<?echo $row['username']?>')"
the important part here is, outside of <? ⦠?>
pure html , never looked @ php interpreter. therefore, part relevant php code inside <? ⦠?>
, namely echo $row['username']
. here, 1 not need escaping.
your second example, in contrast
echo('<button type="button" id="button'.$ctr.'"onclick="showmapsinfo(\''.str_replace("'", "\\'", $maps_name).'\', \''.str_replace("'", "\\'", $ctr).'\');"><img src="img/maps_logo.gif"></button><br/>');
is written purely in php, no surrounding html. therefore, have careful quotes. let's build scratch see happens here. when build this, start with
echo('<button type="button" id="button1" onclick="showmapsinfo(\'...\');"><img src="img/maps_logo.gif"></button><br/>');
because single quotes used string delimiters, must escaped inside string \'
. part inside javascript function. put simpler, above code boils down to
echo('showmapsinfo(\'...\');');
which results in
showmapsinfo('...');
when want insert dynamic parts instead of '...' part, need end string '
, concatenate .
. suppose wanted insert variable $foobar
in there, write:
echo('showmapsinfo(\''.$foobar.'\');');
which results in
showmapsinfo('<value of $foobar>');
your example not insert $foobar
string, rather following expression:
str_replace("'", "\\'", $maps_name).'\', \''.str_replace("'", "\\'", $ctr)
which uses str_replace
in order again escape content, little twist: not escaped php, resulting javascript! every single quote '
becomes escaped single quote \'
in output, need write \\'
because backslash needs escaped itself, in order produce backslash output.
Comments
Post a Comment