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.