开发者

Escape brackets on php for javascript

开发者 https://www.devze.com 2023-01-14 05:53 出处:网络
For example i\'ve a php script with this content: <?php $msg = addslashes(\"I\'m a message. The what happened >:(\");

For example i've a php script with this content:

<?php
$msg = addslashes("I'm a message. The what happened >:(");
echo "<script>alert($msg); return false;</script>";
?开发者_JAVA技巧>

But the alert get broken by the last "(". How can i solve this?


You should enclose alert parameter with quotes:

echo "<script>alert('$msg'); return false;</script>";

What your code outputs to the browser was:

<script>alert(The what happened >:(); return false;</script>

which is not a valid javascript, after putting the quotes, it becomes:

<script>alert('The what happened >:('); return false;</script>

which is valid javascript.


You need to put it in a JavaScript string, otherwise it gets interpreted like this, which is meaningless and causes an error:

<script>alert(The what happened >:(); return false;</script>

Notice the single quotes in the alert() call which denote a JavaScript string (double quotes work too):

<?php
$msg = "The what happened >:(";
echo "<script>alert('$msg'); return false;</script>";
?>

It is also a good idea to escape the content inside to mitigate XSS, using htmlspecialchars().


The other answers are along the right lines, but it is not sufficient to just put quotes around the string, if it can be any arbitrary string. If the string itself contains a quote, backslash, or newline, that will break the JavaScript string literal. If the string contains </script (or just </ in some cases) that will break the <script> block. In either case, if user-supplied input is involved, that gives you a big old cross-site-scripting security hole.

Whilst you may not need it for this specific value of $msg, it's a good idea to get used to JS-string-literal-escaping any text you output into a JS string. Whilst you can do this manually by adding backslashes, it's generally much easier to just use the built-in JSON encoder, which will work for other types like arrays and objects as well as strings.

<script type="text/javascript">
    alert(<?php echo json_encode($msg); ?>);
    return false; // huh? return, in a <script> block??
</script>


alert() accepts a string argument; you must enclose the text you're passing to it in quotes (either single or double) and insure that any matching quotes within the string are escaped by backslashes.

In your case single quotes would suffice:

echo "<script>alert('$msg'); return false;</script>";


Depending on the context, you might also just do:

<?php
    $msg = "The what happened >:(";
?>

<script>alert("<?php echo $msg ?>"); return false;</script>

If there is no need to echo HTML or JavaScript code, then don't do it. It is easier to maintain .

0

精彩评论

暂无评论...
验证码 换一张
取 消