逃脱"php中带有echo的字符 [英] Escape " character in php with echo

查看:31
本文介绍了逃脱"php中带有echo的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简短的问题:

echo '

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

谢谢!

解决方案

您可以尝试以下方法:

echo '

所以,不是转义 " 双引号.我们转义 ' 单引号.读取 html 输出时会更清楚.

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

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

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

编辑 2:此外,正如@deceze 所建议的那样,如果变量 $filename 可能包含引号或您可以使用的某些内容 htmlentities() ,如果 filename 的值,它将保护您免受 XSS是来自用户的输入.你可以像下面这样使用它:

<button type="button" id="add" onClick="addAsset('<?= htmlentities($filename) ?>');"><?= htmlentities($文件名) ?></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.

这篇关于逃脱&quot;php中带有echo的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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