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

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; ?>")';

Related

php javascript json parse escape characters

I currently have a webpage that need to use javascript to parse variables from php.
I do things like this:
data.notices = JSON.parse('<?php echo json_encode($notices) ?>');
However, when there is single or double quotes in the $notices variable, javascript console return errors.
How can I get the variables correctly?
This code doesn`t return error
<?
$notices = array('sad'=>'asd as" asd', 'asd"sdf '=>'asdasd" \' asd ads');
?>
<script>
data = new Object();
data.notices = JSON.parse('<?php echo addslashes(json_encode($notices)) ?>');
</script>
$a='b' will be converted to "b"(note the quotation mark) by json_encode
just write JSON.parse(<?php echo json_encode($notices) ?>);(remove ') will be ok.
I found that it is the problem caused by the fact that I did not escape the characters before inserting to database.
You are one extra operation. If you want message as javascript variable you can directly get like
data.notices = <?php echo json_encode($notices) ?>;
// and access like this
// data.notices[0] or data.notices['alert']

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

php, how to convert special characters to text?

xxxi have the_title() that returns some text, in this case Blue & Whiny
the problem as we can see is that the & character looks different
how do i turn Blue & Whiny into Blue & Whiny i tryed: htmlspecialchars_decode(the_title()), html_entity_decode(the_title()),htmlspecialchars(the_title()) and nothing.
i want to convert & to &
there is not much code to share, I just do this: <?php the_title() ?> and i get Blue & Whiny. If i use get_the_title() it wont display anything
Any ideas?
Thanks
edit1. ill share some code:
<script type="text/javascript">
function showShareUI() {
var act = new gigya.services.socialize.UserAction();
act.setUserMessage("Check out this article.");
act.setTitle("Trends on Explore Talent - <?php the_title(); ?>");
act.setDescription("<?php get_the_content(); ?>");
act.setLinkBack("<?php the_permalink(); ?>");
act.addActionLink("Check out this article", "<?php the_permalink(); ?>");
var image = {
src: 'http://xxx.com/wp-content/uploads/2011/05/BOTTOM_BANNER.jpg',
href: '<?php the_permalink();?>',
type: 'image'
}
act.addMediaItem(image);
var params =
{
userAction: act, // The UserAction object enfolding the newsfeed data.
onError: onError, // onError method will be summoned if an error occurs.
onSendDone: onSendDone // onError method will be summoned after
,showEmailButton: true
// Gigya finishes the publishing process.
};
gigya.services.socialize.showShareUI(conf, params);
}
function onError(event) {
alert('An error has occured' + ': ' + event.errorCode + '; ' + event.errorMessage);
}
function onSendDone(event)
{
document.getElementById('status').style.color = "green";
document.getElementById('status').innerHTML = 'The newsfeed has been posted to: ' + event.providers;
}
</script>
I've tried everything. This starts to annoy me...
html_entity_decode() is the correct way to do it.
html_entity_decode("Blue & Whiny");
Will produce:
Blue & Whiny
If it's not working, make sure you don't have another issue - such as passing a string to it that is double encoded, or running htmlentities() on the string again later.
Demo: http://codepad.org/BHXGWXJi
Double check with a literal string and var_dump() the output, you should see the decoded version. Then var_dump(the_title()), to make sure you are actually passing what you think you are to html_entity_decode().
html_entity_decode should do the trick. If not, try to specify the third parameter $charset.
Something like:
echo html_entity_decode(the_title(), ENT_QUOTES, 'UTF-8');
the_title() directly prints the title, so adding html_entity_decode() directly around that won't work. You can, however, stop it from printing with its third function argument. E.g.
<?php echo html_entity_decode(the_title('', '', false)) ?>
There's also get_the_title(), which doesn't directly print the title, but it requires the ID of the post you want the title of, in contrast with the_title, which prints the title of the current post in The Loop. So you need to do something like this:
<?php echo html_entity_decode(get_the_title($post->ID)) ?>
And actually, you should be able to simply do:
<?php echo $post->post_title ?>
The only reason these utility functions are there is to escape things for you and add tags and stuff. If you just want the raw input, you can print it directly.
This won't fix all of your issues, though, because you're echoing it inside a JavaScript string, so you need to escape certain characters. json_encode() should do the trick, but see the question "Pass a PHP string to a Javascript variable (including escaping newlines)" for more details.
Try this:
echo(mb_convert_encoding(the_title(), "UTF-8", "HTML-ENTITIES"));
see if this works for ya
$convmap = array (0x0, 0xffff, 0, 0xffff);
//$str = mb_decode_numericentity (the_title(), $convmap, 'UTF-8' );
$str = mb_decode_numericentity ("&", $convmap, 'UTF-8' );
echo $str;
http://www.php.net/manual/en/function.mb-decode-numericentity.php

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.

How to escape Javascript code that is echoed in PHP

I have this code that is captured in the jquery Data object from a php page.
echo "
var $d = $('<div/>', {
id: 'hi' + $('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
$('#textResp').append($d)
";
Problem is, the 's are not escaped. I have tried using /' to escape, but it comes up with an error. I am sure I am doing this wrong, does anyone know where to put the /' instead of '?
You could use a php nowdoc instead of quotes at all which would simplify things:
echo <<<'DOC'
var $d = $('<div/>', {
id: 'hi' + $('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
$('#textResp').append($d)
DOC;
then use whatever you want inside (quote or dquote). This is, of course, unparsed so if $d was actually referring to a php var then you would have problems.
Your apostrophes actually look fine. But, within a double quoted string, PHP will evaluate any string beginning with a dollar sign as a variable and not produce the desired result. Try replace the jquery related instances of $ with \$. Like this:
echo "
var \$d = \$('<div/>', {
id: 'hi' + \$('#textResp').children().length,
class: 'eventdiv',
html: 'hello'
}).hide().fadeIn(3000);
\$('#textResp').append(\$d)
";
use json_encode function in php, it behaves like the escape_javascript function in rails.
just pass a string argument to the json_encode function, and it return the escaped string for you, see the sample code below:
<?php
$form_html = <<HTML
<form action='...' ...>
<input type='...' name='...' ...>
...
</html>
HTML;
?>
var form_html = <?php echo json_encode($form_html); ?>;
$('.remote#create_form').html(form_html).slideDown();
You will need to use \ before all 's.
However, this is puzzling, why do you feel you need escape characters? It appears you are simply echoing this output, if this is between <script /> tags, you should be fine.
PHP will attempt to expand variables, $name, that occur in strings wrapped in double quotes. Since $d looks like a variable to the PHP interpreter, it will try to replace it with the variable's value.
Assuming that you don't have $d defined anywhere, that will produce an empty space and, possibly, a notice (if you are using error level E_NOTICE).
To prevent that from happening, escape dollar signs with a backslash (replace $ with \$)
Use single quotes for your string construction. Only use double quotes when you specifically are including variables that you want evaluated. PHP is trying to evaluate all of those $ references you have in there. By using single quotes, you will avoid many escaping problems.
echo '
var $d = $("<div/>", {
id: "hi" + $("#textResp").children().length,
class: "eventdiv",
html: "hello"
}).hide().fadeIn(3000);
$("#textResp").append($d)
';

Categories