I am dynamically creating an anchor that calls a javascript function. It works with one string parameter but not with two. I believe I am not escaping the quotes around the parameters correctly. In search for an answer I came across the following
onclick="alert('<?echo $row['username']?>')"
and the next one I found left me completely 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 someone would please
-
Explain why the single quotes around username do not have to be escaped?
-
Where there is a “dummies” write up on escaping characters so I could try to decipher the second example.
Let’s examine your first example
The important part here is, that everything outside of
<? … ?>is pure HTML and never looked at by the PHP interpreter. Therefore, the only part that is relevant for PHP is the code inside<? … ?>, namelyecho $row['username']. Here, one does not need to do any escaping.Your second example, in contrast
is written purely in PHP, no surrounding HTML. Therefore, you have to be careful with the quotes. Let’s build this up from scratch to see what happens here. When you build something like this, you would probably start with
Because the single quotes were already used as string delimiters, they must be escaped inside the string with
\'. Now for the part inside the javascript function. Put even simpler, the above code boils down towhich results in
when we want to insert some dynamic parts instead of the ‘…’ part, we need to end the string with
'and concatenate it back together with.. Suppose you wanted to insert a variable$foobarin there, then you would write:which results in
Your example does not insert
$foobarinto this string, but rather the following expression:Which uses
str_replacein order to again escape the content, but with a little twist: It is not escaped for PHP, but for the resulting Javascript! Every single quote'becomes an escaped single quote\'in the output, but you need to write\\'because the backslash needs to be escaped itself, in order to produce a backslash as output.