Escaping characters in JavaScript or PHP [duplicate] - javascript

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)) . ")\"";

Related

escape Hebrew double quote on both php and javascript

I'm working on multi-language site based on php.
For supporting multi-language, I'm using localizing file like below.
[localize.en-US.php]
$lang_code = "en-US";
$is_rtl = false;
.
.
.
define("WORD_EMAIL", "e-mail");
define("WORD_NAME", "name");
.
.
.
Defined words used by two way like below.
[HTML]
<?=WORD_EMAIL?> : <input type="text" name="email"/>
<?=WORD_NAME?> : <input type="text" name="name"/>
[Javascript]
if(frm.email.value==="") {
alert("<?=WORD_EMAIL?> required.");
return false;
}
The problem occured when I'd working on Hebrew.
The word "e-mail" of Hebrew tanslation has a double quote in it.
I tried to escaping double quote.
To escape double quote,
PHP need one backslash, and javascript need one more and one another for backslash.
So I added 3 backslashes before double quote.
it shows propery on javascript alert. but on HTML backslash(for javascript) appears..
Yes, I Know using single quote can solve this simply.
But it occurs an exception among localize files(some French word uses single quote).
Can anyone help about this? Any clues welcome.
You always need to encode or escape values for the context you're embedding them in. When putting anything into HTML, you need to HTML-encode it unless you accidentally want the values interpreted as HTML. When putting anything into Javascript source code, you need to escape it properly there, for which JSON-encoding happens to be the right technique:
<?= htmlspecialchars(WORD_EMAIL, ENT_COMPAT, 'UTF-8'); ?> : <input type="text" name="email"/>
alert(<?= json_encode(WORD_EMAIL); ?> + " required.");
Also see The Great Escapism (Or: What You Need To Know To Work With Text Within Text).
I would argue that your i18n approach of pretty flawed though; "אִימֵיְיל required"* seems like a very insufficient localisation. You will want to look into proper tools like gettext and implementations/analogues of it for Javascript.
* Google translation, I don't speak Hebrew…

php echo outputting html as text

I am trying to use php to construct html code containing onclick="Javascript" within
i keep getting an error saying that i am missing a } within the console, however this is not the case.
despite the error the site displays perfectly
I then followed this post
How should I echo a PHP string variable that contains special characters?
and used the method htmlentities
at first it appeared to work correctly however i must have changed something because now it outputs the html string as text and not displaying the element
this issue is present across different platforms/browsers, so i dont believe that it is cache related problem.
there are other elements within the php script that output the html correctly, it just appears that its this line.
Thanks in advance
echo htmlentities('<h2 class="page_title">' . $db_field['Title'] . '</h2><a onClick="showAndroidToast(' . $_SESSION['user_id'] . ',' . $db_field['ID'] . ')"><img src="/mobile/images/plus.png" style="width:25px;height:25px;float:right;margin-top:15px"></a>');
You should not use htmlentities() on strings that you actually want to be interpreted as HTML, since it will convert the < and > into entities so they display literally. Just call it on the variables that you don't want interpreted:
echo '<h2 class="page_title">' . htmlentities($db_field['Title']) . '</h2><a onClick="showAndroidToast(' . $_SESSION['user_id'] . ',' . $db_field['ID'] . ')"><img src="/mobile/images/plus.png" style="width:25px;height:25px;float:right;margin-top:15px"></a>');
Why such violence?
here is how to output templates using PHP :
<?php
//blablabla my php stuff here...
?>
<h2 class="page_title">
<?=htmlentities($db_field['Title'])?>
</h2>
<a onclick="showAndroidToast('<?=$_SESSION[\'user_id\']?>','<?=$db_field[\'ID\']?>');
<img src="/mobile/images/plus.png" style="width:25px;height:25px;float:right;margin-top:15px">
</a>
Whenever you call htmlentities(), whatever in it will be translated into characters that the browser interprets as literal symbols to show. This is how we can tell browsers to display HTML and code without actually interpreting it. It also allows us to show symbols we don't want the browser to accidentally parse. If you have a string containing HTML that you want to be interpreted by the browser, DO NOT use htmlentities().
You don't want:
print htmlentities("<h1>I have a < and > sign I don't want interpreted</h1>");
You actually do want:
print '<h1>' . htmlentities("I have a < and > sign I don't want interpreted") . '</h1>';
Read the docs: http://php.net/manual/en/function.htmlentities.php

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>
_;

Apart from PHP or JavaScript is there any escape character for browsers?

I have a hidden field that stores value retrieved from the database as given below:
echo '<input type="hidden" value="'.$str.'">';
The problem is that if $str contains text having double quotes, it definitely causes problem for the browser to display accordingly. But using escape character \ in PHP is in vain. Also I tried this:
$str = str_replace('"',"'",$str);
Then I have to replace every single quotes into double (doing the reverse) in the client:
str = str.replace(/'/g,'"');
Although it works fine for me,still it doesn't get rid of bugs. For example, if the original string from the database contains single quote (') , it will also get replaced by double quote (") in the client which is unexpected. So, is there any alternative solution to this problem or is there really any escape character for browsers that can be put in the double quotes in the hidden field?
You can use htmlentities to escape the value
http://php.net/manual/en/function.htmlentities.php
e.g.
echo '<input type="hidden" value="'.htmlentities($str).'">';

Generic way to Escape Quotes in Javascript Variable

I have a form where users can enter any HTML.
var title = "Cool Check This"
As you can see, the variable is having " but it can be also '. It causes an error if there is ". What is better way to fix this? Storing escaped string in database like below?
$title = str_replace('"', "'", $_REQUEST['title']); // Replace double quote with single quote as js variable above is wrapped with double quotes.
Or escape it before showing on page? Anything in jQuery like escape that can help here?
var title="Cool Check This"
Well, you cannot escape it using JavaScript because JavaScript needs to see what you want to escape and you want to escape that. If you use PHP, you can use addslashes() prior to inserting into JavaScript.
Anyways, you should be careful of allowing to insert any HTML. Wrongly escaped HTML (like allowing to insert <script>) can allow to do various dangerous stuff, like stealing all cookies.

Categories