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
Related
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…
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)) . ")\"";
I have a button with an onclick function where i send several php variables to my javascript function. This all works fine except for when i have a ' within the text.
So i would have a button
<button onclick=\"selected_comp('" . preg_replace("/\r|\n/", "", $comp_row['comments']) . "')\"
then i would have a function
function selected_comp(comments){
console.log(comments);
}
I have tried preg_replace and json_encode but both give me errors (json_encode gives me error in general and with preg_replace it works most of the time but whenever this ' character is inside the comments it doesn't work. How can i make sure this gets treated as just plain text whatever character is inside.
error: (index):1 Uncaught SyntaxError: Invalid or unexpected token
From how your PHP code is written, if the text in $comp_row['comments'] is text then the resulting JS code will be
<button onclick="selected_comp('text')">
(where I added the < and > for clarity).
Now if the text is text with ' embedded it will result in
<button onclick="selected_comp('text with ' embedded')">
Then you clearly see why it fires an error.
There are plenty of different solutions to avoid it, like the one suggested by #Terminus.
But maybe it's not easy to apply without deeply changing your PHP script structure.
So here is a suggestion which may appear a bit weird but keeps using your current code organization:
button onclick=\"selected_comp('" .
str_replace(["\r", "\n", "'"], ["", "", "\\'"], $comp_row['comments']) .
"')\"
First you can notice that I changed from preg_replace() to str_replace() (anyway preg_replace() was already overkill).
And the point is that now, not only \r and \n are replaced by "nothing" but also ' is escaped.
If you want your string to be valid javascript string that you can use inside your javascript code (in your example - pass the string to the selected_comp function) you should:
Make sure you don't have line-breaks in your string.
Make sure you don't have quotes inside your string (Note here it depends on the quotes you use in your code - single/double).
So you can:
str_replace(["\r", "\n"], ['\r', '\n'], $comp_row['comments']);
str_replace("'", "\\'", $comp_row['comments']);
And in your code:
<button onclick=\"selected_comp('".
str_replace("'", "\\'",
str_replace(["\r", "\n"], ['\r', '\n'], $comp_row['comments'])
) .
"')\"
I used ' because you used it in your original function.
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>
_;
I have this row that gives me an error because the value contains HTML Code.
document.getElementById(\'longstory\').value = \''.$row['longstory'].'\';
Is there any easy way to like encode it during passing and then when showing it in my value
<textarea class="form-control" id="longstory" name="longstory" placeholder="Longstory"></textarea><br />
to get it show as HTML for the user in the end?
Try this:
echo "document.getElementById('longstory').value = " . json_encode(html_entity_decode($row['longstory'])) . ";";
html_entity_decode() will interpret HTML entity codes in the value, converting them into normal PHP characters. Then the output of json_encode() will be Javascript syntax for the value.
The problem isn't that it contains HTML, the problem is that it contains characters that aren't permitted in a Javascript string, such as unescaped quotes and literal newlines. json_encode encodes everything properly.
Try use the htmlspecialchars and addslashes functions before passin to the js.
document.getElementById(\'longstory\').value = \''.addslashes($row['longstory']).'\';