Skip to content Skip to sidebar Skip to footer

Escape " Character In Php With Echo

Short question: echo ''; this creates a button with an onClick function addAs

Solution 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?><buttontype="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:

<buttontype="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.

Solution 2:

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

<buttontype="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));

Solution 3:

Use an escaped single quote \':

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

Post a Comment for "Escape " Character In Php With Echo"