how to escape html / special strings in javascript - php

I have a php / javascript scrip which needs to print some text. unfortunately it seems that the js breaks down if the string has special characters such '
Below is a snippet from the script. $messageContent and $subject are the strings with html tags. (actually "'" characters) .
echo '
<script language="javascript">
function SelectRedirect(){
switch(document.getElementById(\'s1\').value)
{
';
echo '
case "?vrj_name='.$vrj_name.'":
window.location="?vrj_name='.$vrj_name.'&messageContent='.$messageContent_vrj.'&from_email='.$from_email.'&email='.$email.'&subject='.$subject.'";
break;
';
}
I added a function in php to replace "'" with "\'" and it works (the js executes successfully ) but I can't get ride of them when I display them in the webpage .

The best way to do this is to encode the values using json_encode. Here is a simple example:
<?php
$name = "Jason's Bakery";
?>
<script>
var name = <?php echo json_encode($name); ?>;
DoSomethingWithName(name);
</script>
This can be used for integers, strings, and other values. Keep in mind that it will add quotes as needed, so you need to assemble and encode a "whole value at once". In your example of using the URLs, you need to use the PHP urlencode() function to encode them FIRST, and then pass it through json_encode to convert to a javascript value. And if you are placing that inside of an HTML attribute, like onclick, you need to further pass it through htmlspecialchars(..., ENT_QUOTES) and then place it in double quotes.
http://php.net/manual/en/function.json-encode.php
So for example, you need to build a URL in PHP and then use it in javascript...
<?php
$name = "Jason's \"Awesome\" Bakery";
$url = "http://site.com/page.php?name=" . urlencode($name);
?>
<script>
var name = <?php echo json_encode($name); ?>;
DoSomethingWithName(name);
</script>
<input type="button" onclick="<?php echo htmlspecialchars('window.location = ' . json_encode($url) . ';', ENT_QUOTES); ?>" value="Click Me" />
Which results in something like this:
<script>
var name = "Jason's \"Awesome\" Bakery";
DoSomethingWithName(name);
</script>
<input type="button" onclick="window.location = "http:\/\/site.com\/page.php?name=Jason%27s+%22Awesome%22+Bakery";" value="Click Me" />
Needless to say, you do not want to do without these:
http://php.net/manual/en/function.json-encode.php
http://www.php.net/manual/en/function.urlencode.php
http://www.php.net/manual/en/function.htmlspecialchars.php

Due to respects of readability and future maintainability, I'd like to point out a few things which may help you out.
First, I see you're generating HTML elements in a PHP string. This isn't inherently bad, but when your string wraps across 2 or more lines, it becomes increasingly difficult to manage. Instead, you may want to think about escaping PHP for outputting HTML portions, and re-entering PHP for logical portions. You can escape PHP and enter HTML within if statements, function declarations etc, so there's really no good reason not to. Look at the following example (this solution also escapes the strings in an appropriate manner where its value can contain single quotes, double quotes or line breaks):
<?php
function urlFriendly($input) {
return urlencode($input);
}
function jsFriendly($input, $urlFriendly = True) {
$output = htmlentities($input, ENT_QUOTES);
// Double quotes in PHP translate "\n" to a newline.
// Single quotes in PHP keep the literal value.
$output = str_replace("\r\n", '\n', $output); // Windows support
$output = str_replace("\n", '\n', $output); // Linux support
if($urlFriendly) { // Encode for use in URLs
$output = urlFriendly($output);
}
return $output;
}
$vrj_name = 'vrj';
$messageContent_vrj = 'message content';
$from_email = 'from email';
$email = 'email';
$subject = 'subject line';
?>
<script type="text/javascript">
function SelectRedirect() {
switch(document.getElementById('s1').value) {
case '?vrj_name=<?php print jsFriendly($vrj_name);?>':
var toloc = '?vrj_name=<?php print jsFriendly($vrj_name);?>';
toloc += '&messageContent=<?php print jsFriendly($messageContent_vrj);?>'';
toloc += '&from_email=<?php print jsFriendly($from_email);?>';
toloc += '&email=<?php print jsFriendly($email);?>';
toloc += '&subject=<?php print jsFriendly($subject);?>';
window.location = toloc;
break;
}
</script>

just like that
$escaped_string = addslashes($unescaped_string);
either before
$messageContent = addslashes($messageContent);
$subject = addslashes($subject);
or even inline
echo '
case "?vrj_name='.$vrj_name.'":
window.location="?vrj_name='.$vrj_name.'&messageContent='.addslashes($messageContent).'&from_email='.$from_email.'&email='.$email.'&subject='.addslashes($subject).'";
break;
';

Related

Passing a PHP variable to a java-script function

im trying to pass a value to a java-script function. but when i click the link i get a
Uncaught SyntaxError: Unexpected identifier
here is the code
<?php
include_once("php_includes/check_login_status.php");
$routeHTML = '';
$sql = "SELECT user,title FROM route";
$query = mysqli_query($db_conx, $sql);
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$title = $row["title"];
$user = $row["user"];
$routeHTML .= '<p>Planned By '.$user.'</p>'.$title.'<br />';
}
?>
i echo the $routeHTML in a div tag
you forgot to add quotes for the javascript:
$routeHTML .= '<p>Planned By '.$user.'</p>'.$title.'<br />';
You'll have to surround your string with a '' quotes like this...
$routeHTML .= '<p>Planned By '.$user.'</p>'.$title.'<br />';
The Parameter to your JS function is undefined (since the parsed HTML is missing quotes - JS assumes title is an undefined variable).
You forgot to escape the quotes, do like this:
fetchdata(\''.$title.'\')
Otherwise php will not render the ' properly and you get an error.
You can pass a php variable to a javascript function in this way:
<input type="button" value="Send" onClick="js_function('<?php echo $var; ?>')">
It's generally not recommended to make inline Js (as an attribute of the tag).
So, i encourage you to separate javascript from html code, like this :
Html:
$routeHtml = '<p>Planned By '.$user.'</p>'.$title.'<br />';
Js (with jQuery, but also work for vanillaJs):
$(document).ready(function(){
$(".MyLink").click(function(e){
fetchData($(this).data("title"))
});
});
Note the data-title attribute, the data-* attributes are intended to store custom data, so it's a great way to exchange informations between php and Javascript inside templates.
More info about data-* attributes : http://webdesign.tutsplus.com/tutorials/htmlcss-tutorials/all-you-need-to-know-about-the-html5-data-attribute/

How to output Javascript from PHP files with PHP variables embedded in JS code?

I would like to move JS code snippets out of PHP files and into their own files in order to make code a lot cleaner and easier to maintain. For example, I have this function:
function load_script($fieldname)
{
return
'var help = function () {alert(' . '"EDITOR HELP:\n\n' .
'blah blah.\n\n' .
'more blah blah.\n\n' .
');}' . "\n" .
'var options = { handler: help, title: "Editor help" };' . "\n" .
'var converter = Markdown.getSanitizingConverter();' . "\n" .
'var editor = new Markdown.Editor(converter, "-'.$fieldname.'", options);' . "\n" .
'editor.run();' . "\n";
}
Notice the $fieldname PHP variable.
The idea is to store the JS portion in a .js file. Then I'd read it in as plain text in order to output in the return statement. In other words, something like this:
function load_script($fieldname)
{
$output = file_get_contents("load_script.js");
return $output;
}
Obviously the problem is that this would not substitute $fieldname with the corresponding value.
My current thought on this is to run $output through string subsitution:
function load_script($fieldname)
{
$output = file_get_contents("load_script.js");
$output = str_replace("some_unique_identifier", $fieldname, $output);
return $output;
}
Is there a better approach?
EDIT:
I should add some of the motivation behind this:
First, the example given is ugly and hard to maintain for anything but the simplest JS snippets. Lots of room for mistakes.
Second, editors aren't very helpful in terms of checking syntax and highlighting when you mix things up this way.
Third, having JS live on its own files makes it easier to run a minification script that crunches on the entire site (so you don't have to manually maintain minification).
You could use a template engine to do this (such as Smarty for instance). Simply write your JS files using the template variables where your PHP variables would be, and load them through PHP.
You could even roll your own simple one. Something like:
// in JS file:
function myFunc() {
alert("hello %s");
}
// in PHP file:
<?PHP
//... code to open JS file and load into string....
echo sprintf($contentsOfJSFile, "John Doe");
?>
RESULTING OUTPUT:
function myFunc() {
alert("hello John Doe");
}
As someone already mentioned, A JS file is just as HTML, which in turn, is just like a PHP file. So create you javascript file like this
<?php
//my_script.php
?>
<script>
var foo = "<?= $bar ?>";
</script>
And then, in your php:
$bar = 'some value';
include('my_script.php');
Unfortunately, not really, or, at least, not out of the box. There are some clever solutions such as Backbone which might make your task easier or more sane, but might also require a rewrite.
In a nutsehll, outputting js is the same as outputting html. You can embed php variables, but you're subject to the same rules as far as escaping quotes and literals vs references. It can get ugly and tedious pretty quickly.
What I do depends on the JS and the number of variables. Sometimes I make strings for all my js and then glue them together, like
$js_function_pt1 = "var help = function() { ..."
$js_function_pt2 = "..."
return $js_function_pt1 + $fieldname + $js_function_pt2 + ....
if you can keep all single quotes in your js, you have a little extra luxury in that you can enclose your js output in double qoutes, and then variable references from php will interpreted as variables and evaluated.
$output = " var help = function() { alert('blah blah $fieldname') } "

How to concatenate PHP and JavaScript strings with quotes to evaluate properly

I have one page iframed inside of another. The child page communicates with the parent page by using the sendMessage() function. The parent page runs eval() on the message that is received from the child page.
This is the code that constructs the message:
var msg_string = '$("body").append("<?php echo $content; ?>")';
var send_string = "sendMessage(\'" + msg_string + "\', '<?php echo $receiver_domain; ?>')";
setTimeout(send_string, <?php echo $delay; ?>);
The problem among other things is that the $content variable contains HTML and the double quotes in things like id="test" do not play well with all of this concatenation. I am at a loss trying to figure this out.
I have already attempted to escape the quotes in $content by converting them to " but that resulted in the browser placing div ids in double double quotes (""test"").
** Update **
Using the json_encode method does work for getting the data to the parent page. It's a much easier solution than what I had been doing (I had already accomplished this much but figured something was amiss). That said, the eval of the data still fails if there are double quotes in a div id="test". A string of just "test" works, but it actually puts "test" verbatim. This is the javascript source in the html after using the json method:
var msg_string = '$("body").append("<div class=\\\"test\\\">HEY WHATS UP<\/div>");';
var send_string = "sendMessage(\'" + msg_string + "\', 'http://domain.com')";
setTimeout(send_string,500);
This fails at the eval. Putting an alert in place of the eval yields this:
$("body").append("<div class="test">HEY WHATS UP</div>");
Any ideas?
** Update 2 **
So I FINALLY figured this out. It was a combination of the three answers below. The json answer tipped me off. Basically the double quotes needed to be tripple backslashed so that by the time it go to the eval, everything would be read properly.
I ran into a few other snags, including /r/n characters in the html...which I removed with str_replace and also an apostrophe...which was in an inner html element...I replaced that with the appropriate html entity and BAM!
Here is the code:
function escapeQuotes(string){
var quotes_regex = new RegExp("\"", "g");
return string.replace(quotes_regex, "\\\"");
}
var msg_string = '$("body").append(<?php echo json_encode( str_replace("\r\n", '', $content) ); ?>);';
var send_string = "sendMessage(\'" + escapeQuotes(msg_string) + "\', '<?php echo $receiver_domain; ?>')";
setTimeout(send_string,<?php echo $delay; ?>);
I upvoted everyone's answer since I used bits of everything. Thank you so much!
JSON is your friend.
var msg_string = '$("body").append(<?php echo json_encode($content); ?>)';
If your only concern is double quotes, why not just replace them with an escaped string?
var msg_string = '$("body").append("<?php echo str_replace("\"", "\\"", $content); ?>")';
I can't exactly test, but that would seem to work to me.
You need to escape using str_replace
$search = array("'", '"');
$replace = array("\'", '\"');
var msg_string = '$("body").append("<?php echo str_replace(search, replace, $content; ?>")';

How to escape string from PHP for javascript?

lets imagine a form editor, it can edit available values. If the data contains " character (double quote) it "destroys" HTML code. I meant, lets check the code: so I generate HTML:
onclick="var a = prompt('New value: ', '<?php echo addslashes($rec[$i]); ?>'); if (a != null)....
and it results in
onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....
and this makes JS work impossible, so that it ruins the code. With single qoute ' it works OK. mysql real escape does the same.
How to escape any string so that it won't ruin javascript?
json_encode looked OK, but I must be doing something wrong, its still bad: heres a screenshot how Firefox sees it - it inserts a "bad" double quote! The value is just a simple number:
http://img402.imageshack.us/img402/5577/aaaahf.gif
and I did used:
('Ird be az új nevet:', <?php echo json_encode($rec['NAME']); ?>); if (a) {
The value of the onclick attribute should be escaped like any other HTML attribute, using htmlspecialchars(). Actual Javascript strings inside the code should be encoded using json_encode(). For example:
<?php
$message = 'Some \' problematic \\ chars " ...';
$jscode = 'alert('.json_encode($message).');';
echo '<a onclick="' . htmlspecialchars($jscode) . '">Click me</a>';
That being said... onclick (or any other event) attributes are so 2005. Do yourself a favor and separate your javascript code from your html code, preferably to external file, and attach the events using DOM functions (or jQuery, which wraps it up nicely)
onclick="var a = prompt('New value: ', 'aaaa\"aaa'); if (a != null) { v....
Your problem is highlighted in bold.
You can't quote a variable declaration
you shouldn't need to escape the double quote once this is removed since it is within single quotes.
Should look like this -
onclick="newFunc();"
<script>
function newFunc() {
var a = prompt('New value: ', 'aaaa"aaa');
if (a != null) { v....
}
</script>
...onclick="new_func();"...
<script>
function new_func() {
var a = prompt('new value:','<?php code; ?>');
if (a) { <!--javascript code--> } else { <!--javascript code--> }
}
</script>
I'm really just re-wording what #Marshall House says here, but:
In HTML, a double quote (") will always end an attribute, regardless of a backslash - so it sees: onclick="var a = prompt('New value: ', 'aaaa\". The solution that #Marshall offers is to separate your code out into a function. This way you can print escaped PHP into it without a problem.
E.g.:
<script>
// This is a function, wrapping your code to be called onclick.
function doOnClickStuff() {
// You should no longer need to escape your string. E.g.:
//var a = prompt('new value:','<?php echo $rec[$i]; ?>');
// Although the following could be safer
var a = prompt('new value:',<?php json_encode($rec[$i]); ?>);
if (a) { <!--javascript code--> }
else { <!--javascript code--> }
}
</script>
<someelement onclick="doOnClickStuff();"> <!-- this calls the javascript function doOnClickStuff, defined above -->

Printing varchar php variable inside the javascript function

I am trying to print a variable value within the javascript function. If the variable is an integer ($myInteger) it works fine, but when I want to access text ($myText) it gives an error.
<?php $myText = 'some text';
$myInteger = '220';
?>
<script type="text/javascript">
<?php print("var myInteger = " . $myInteger . " ;\n");?> //works fine
<?php print("var myText = " . $myText . " ;\n");?> //doens't work
</script>
Can anyone explain to me why this happens and how to change it?
The problem with your code from the question is that the generated Javascript code will be missing quotes around the string.
You could add quotes to the output manually, as follows:
print("var myText = '". $myText. "';\n");
However, note that this will break if the string itself contains quotes (or new-line characters, or a few others), so you need to escape it.
This can be dealt with using the addslashes() function, among others, but this may still have issues.
A better approach would be to use PHP's built-in JSON functionality, which is designed specifically for generating Javascript variables, so it will do all the escaping for you correctly.
The function you're looking for is json_encode(). You'd use it as follows:
print("var myText = ". json_encode($myText). ";\n");
This will work with any variable type -- integer, string, or even an array.
Hope that helps.
Without more code we don't really know what you're trying to do or what error you're getting (or from where even), but if I had to guess:
If you are putting a string of text into a javascript variable, you probably need to quote it.
<?php print("var myText = '" . $myText . "' ;\n");?>
---^^^-------------^^^----
// Or even better:
<?php print("var myText = '$myText' ;\n");?>
ADDENDUM Per the comment below, don't use this if you expect your $myText to contain quotes.

Categories