What is a proper way to escape HTML for Javascript function? - javascript

I'm getting Uncaught SyntaxError: Unexpected identifier
due of the Java-Script clashing syntax or single and double quote.
In the source file,the $str is escaped as special chars but not sure why Javascript will hit error.
What is the Correct/Proper way to escape it with single or double quote inside a string for Javascript function use purpose?
Below is my code :
<?php
$str = 'I\'m John Doe < lol > "19" ! ?';
?>
<div onclick="alert('<?php echo htmlspecialchars($str); ?>')">Test</div>
<div onclick="alert("<?php echo htmlspecialchars($str); ?>")">Test</div>

The important thing to note here is that you don't just have JavaScript. You have JavaScript in an HTML attribute, so you have to escape for JS then for HTML.
json_encode will escape for JS. It will also add quotes around strings, so do you don't need to do that yourself.
htmlspecialchars will escape for HTML.
onclick="alert(<?php echo htmlspecialchars( json_encode( $str ) ); ?>"

Any time you're using strings in the context of JavaScript, use JSON-encoding. JSON is compatible with JavaScript parsers, and all of the escaping needed will be done for you.
var str = <?php json_encode($str) ?>;

Related

How to escape string in onClick="function(string)"

I have to echo a string that could contain everything into the following html line:
...
I don't know how to properly escape the string I pass with php, there seem to be many problems and json_encode is not working as it wraps the output in double quotes which is not working as the double quotes already begin after "onclick=".
Just replacing single quotes also doesn't work as "\'" would be replaced to "\'".
Any ideas?
you can use addslashes() function.
Try this:
<?php
$str = addslashes('What does "yolo" mean?');
echo($str);
?>
Use PHP addslashes function:
...
As none of the answers worked, I had a closer look at the problem and came up with this solution:
function clean_param($string){
// escapes all single quotes and backslashes
$single_qu_esc = addcslashes($string, "'\\");
// escapes the resulting string for html
return htmlentities($single_qu_esc, ENT_QUOTES);
}
you can wrap your string with htmlspecialchars, that should do the job.
...

JSON.parse string with single and double quotes?

I am saving an array as json and parsing it again upon load. However, after adding HTML with both single and double quotes, this has stopped working.
How can I escape the quotes?
JSON.parse('[["",null,null,null,null,null,"","","<span onclick=insertRow()><i class='fa fa-plus-circle fa-lg'></i></span>"]]');
uncaught SyntaxError: missing ) after argument list
EDIT:
My string is saved in database using JSON.stringify. It ends up in the following format:
[["ad",null,true,false,true,false,"","","<span onclick=insertRow()><i class='fa fa-plus-circle fa-lg'></i></span>"]]
when Im loading it again, I do it like follows:
var phpsave = JSON.parse('<?php echo $result->save; ?>');
If im escaping the single quotes before saving, the escaping just dissappears upon loading..
You're dynamically producing Javascript source code. You need to ensure that what you're producing is syntactically valid. The easiest way to produce valid Javascript literals from PHP is using json_encode:
var phpsave = JSON.parse(<?php echo json_encode($result->save); ?>);
// look ma, no quotes! ^ ^
But wait, aren't you passing JSON to your Javascript? Isn't JSON already valid Javascript? Why, yes, yes it is. So you can leave out that step:
var phpsave = <?php echo $result->save; ?>;
Of course, you might want to ensure that you're really passing valid JSON here first before you start outputting random Javascript code.
You can escape it like
var r = JSON.parse('[["",null,null,null,null,null,"","","<span onclick=insertRow()><i class=\'fa fa- plus - circle fa- lg\'></i></span>"]]');

Escaping characters in JavaScript or PHP [duplicate]

I'm looking for the best way to escape some Javascript text in PHP, and json_encode is the wrong tool for the job.
The problem comes from this line:
echo " onclick=\"SwitchDiv('" . $option . "')\"";
If there's an apostrophe in $option, this is a juicy ball of client-side fail. But doing a straight json_encode (which works perfectly well in other contexts) doesn't help:
echo " onclick=\"SwitchDiv(" . json_encode($option) . ")\"";
That creates an output string of onclick="SwitchDiv("athlete's foot")", resulting in premature termination of the onclick value. (Which also happens if I enclose the onclick value in single quotes.)
Is there an elegant way around this? Should I just funnel the json_encode output through a regex that will escape the single quotes?
json_encode is the right tool for the job. Your problem arises from the fact that you are also including that Javascript in an HTML attribute, thus it also needs to be htmlspecialchars-encoded.
echo " onclick=\"SwitchDiv(" . htmlspecialchars(json_encode($option)) . ")\"";

Escaping special characters in javascript in a link

Not sure if I'm asking the right question. But this is what I want:
I have this code:
$content = rawurlencode(file_get_contents("c://Server/www/Codice/LOGS/".$user."/".$file));
$thelist .= "<li class=files><a href=javascript:alert('".$content."') class=filelink>".$file."</a></li>";
echo $thelist;
What I want is to alert (actually this is just a test, I want to use the $content as argument in a function) the $content when I click the link. How should I do this?
I'm guessing it would work fine if the file is a simple txt file. But the file I'm using here is a C++ program, which contains characters <>, obviously
First you need to get the file contents. This is pretty straight forward, except that you need to make sure that $user and $file don't contain any unexpected characters, such as "../" that would take you outside of the designated directory. Example using preg_match():
if (!preg_match ('/^[\w\d]+$/', $user) ||
!preg_match ('/^[\w\d]+$/', $file)) {
/* Error */
return;
}
$content = file_get_contents("c://Server/www/Codice/LOGS/".$user."/".$file);
Next, you need to turn the contents into a valid javascript string. To do this, you need to escape the backslash, double or single quote and line terminator characters (including U+2028 and U+2029). I believe the easiest way to do this is using json_encode():
$code = json_encode ($content);
The code (after the javascript: part) is technically a URL so it has to be escaped with rawurlencode():
$href = 'javascript: ' . rawurlencode ("alert ($code)");
The href (and also the file name) then needs to be suitably escaped with htmlspecialchars() to be used as an HTML attribute. I think this can actually be skipped for $href because the string is HTML-safe after rawurlencode()
$href_h = htmlspecialchars ($href);
$file_h = htmlspecialchars ($file);
Now we are finally ready to output the result. I like using HEREDOC when mixing variables with HTML:
echo <<<_
<li class=files><a href="$href_h" class=filelink>$file_h</a></li>
_;

echo in php javascript variable single and double quotes

I know that's the stupid question but i don't get code to work...i would like to echo this in php:
<img title="vlc" id="vlc-playlist" src="./img/vlc.png" onclick="window.location='vlc.php?user=test&pass=testpass&type=vlc'">
i im working with datatables jquery plugin so i need to put this img tag into $row[7].
my try to echo this is here:
$row[7] = '<img title="vlc" id="vlc-playlist" src="./img/vlc.png" onclick="window.location=vlc.php?user='.$row[1].'&pass='.$row[2].'&type=vlc">';
and i im getting this for output:
<img title="vlc" id="vlc-playlist" src="./img/vlc.png" onclick="window.location=vlc.php?user=test&pass=testpass&type=vlc">
$row[1] = username
$row[2] = password
so how to put single quotes to get result like on the first example?
Many Thanks.
Escape the quote symbol with backslash:
$row[7] = '<img title="vlc" id="vlc-playlist" src="./img/vlc.png" onclick="window.location=\'vlc.php?user='.$row[1].'&pass='.$row[2].'&type=vlc\'">';
Single quoted
The simplest way to specify a string is to enclose it in single quotes
(the character ').
To specify a literal single quote, escape it with a backslash (\).
http://www.php.net/manual/en/language.types.string.php
Use the escape sequence \' to add a single quote to the string.
For better understanding, consider reading the manual: http://www.php.net/manual/en/language.types.string.php
You need to escape those single quotes
$row[7] = '<img title="vlc" id="vlc-playlist" src="./img/vlc.png" onclick="window.location=vlc.php?user=\'.$row[1].'&pass='.$row[2].'&type=vlc\'">';
try this :
<?php
echo "<img title=\"vlc\" id=\"vlc-playlist\" src=\"./img/vlc.png\" onclick=\"window.location='vlc.php?user=test&pass=testpass&type=vlc'\">\n";
?>

Categories