Escape " character in php with echo

末鹿安然 提交于 2019-12-23 20:05:05

问题


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!


回答1:


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.




回答2:


The end result you'll want to end up with is:

<button type="button" id="add" onClick="addAsset(&quot;example.png&quot;);"> example.png </button>

Otherwise you'll have broken HTML syntax. The alternative is non-conflicting quotes:

<button type="button" id="add" onClick="addAsset('example.png');"> example.png </button>

But you'll still have to escape/encode your input correctly, in case $filename ever contains an undesirable character. The value of the onClick attribute must be valid Javascript, and valid HTML. So:

printf('<button type="button" id="add" onClick="%s"> %s </button>',
       htmlspecialchars(sprintf('addAsset(%s)', json_encode($filename))),
       htmlspecialchars($filename));



回答3:


Use an escaped single quote \':

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


来源:https://stackoverflow.com/questions/46993915/escape-character-in-php-with-echo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!