转义PHP中的字符与回声 [英] Escape " character in php with echo

查看:38
本文介绍了转义PHP中的字符与回声的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简短问题:

  echo'< button type = button id = add onClick = addAsset( '。$ filename。');> ‘。$ filename。’< / button>’; 

这将创建一个带有onClick函数的按钮addAsset(example.png);
但是我想拥有addAsset( example.png)我该如何转义字符?



谢谢!

解决方案

您可以尝试以下方法:

  echo'< button type = button id = add onClick = addAsset(\''。$ filename.'\');>'。$ filename。'< / button>' ; 

因此,不要转义 引用。我们在转义单引号。



编辑:更好的方法是在php块之外编写html块,如下所示: :

 <?php 
//您的PHP代码
?>
< button type = button id = add onClick = addAsset('<?= $ filename?>');><?= $ filename?>< /按钮>
<?php
//更多PHP代码
?>

如您所见,它将更具可读性,并且不需要转义。您可能会注意到,它使用<?= $ filename?> ,这只是<?php echo $ filename的缩写; ?> 。在从HTML转义

编辑2:另外,由于变量 $ filename 可能包含引号,因此@deceze建议或其他可以使用 htmlentities()的东西,如果 filename 的值,它将保护您免受XSS的攻击
是用户的输入。您可以像下面这样使用它:

 < button type = button id = add onClick = addAsset(' <?= htmlentities($ filename)?>');><?= htmlentities($ filename)?>< / button> 

也请检查 @ deceze的答案,以更好地了解在这种特殊情况下如何保护代码不受xss的影响。


Short question:

echo '<button type="button" id="add" onClick="addAsset('.$filename.');"> '.$filename.' </button>';

this creates a button with an onClick function addAsset(example.png); But i'd like to have addAsset("example.png") how do i escape the " character?

Thank you!

解决方案

You can try the following instead:

echo '<button type="button" id="add" onClick="addAsset(\''.$filename.'\');"> '.$filename.' </button>';

So, instead of escaping " double quote. we are escaping ' single quote. Which will be more clear when reading the html output.

Edit: Better approach would be to write html blocks outside of php blocks like the following:

<?php 
//Your PHP COde
?>
<button type="button" id="add" onClick="addAsset('<?= $filename ?>');"><?= $filename ?></button>
<?php 
//More PHP COde
?>

As you can see it will be more readable and no escaping would be required. And as you might notice this uses <?= $filename ?>, that is just short for <?php echo $filename ; ?>. Learn more about all this in Escaping from HTML

Edit 2: Also, as @deceze have suggested wht if variable $filename might contain quote or some thing you can use the htmlentities() for that, it will protect you against XSS if the values of filename is an input from user. you can use it like below:

<button type="button" id="add" onClick="addAsset('<?= htmlentities($filename) ?>');"><?= htmlentities($filename) ?></button>

Also, check @deceze's Answer below for better understanding of how to protect your code from xss, in this particualr situation.

这篇关于转义PHP中的字符与回声的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆