Returning print_r as a string (PHP) - php

Am I doing this correctly? As I understand it, if I define the "return" value as true when I call print_r, it should return a string. I have the following function:
function alert($string) {
echo '<script>alert("' . $string . '");</script>';
}
And when I pass that function a regular old quote-encapsed string, it works just fine and dandy, but when I feed it this:
alert(print_r($array,true));
Nothing happens and I don't see an error, yet echoing print_r($array,true) works. Thanks for any help you can offer, I'm just trying to understand what's going wrong here even though it is obviously a very minor problem.

Use
<script>
alert(<?php echo json_encode(print_r($array, true)); ?>);
</script>
instead. Note the use of json_encode - this is to prevent any ' or other JS-metacharacters from introducing a JS syntax error, e.g.:
<?php
$name = "Miles O'Brien"; // note the '-quote in there
?>
<script>
alert('<?php echo $name ?>');
</script>
would give you:
alert('Miles O'Brien');
^-- start of string
^--end of string
^^^^-- unknown variable/function.

Your alert function has two problems handaling that input.
first, as metioned, your JS is missing qutes.
Second, the new lines should be converted to the string '\n'. otherwise your call to the alert function (in the js) will end in another line, which is not correct. for example:
alert("hello
world");
is invalid syntax.
so, this alert function will probably work:
function alert($string) {
$string=preg_replace('/\n/m','\\n',$string);
echo '<script>alert("' . $string . '");</script>';
}

print_r (as well as var_dump) outputs its content to stdout. However, you can control this behaviour with PHP's buffers.
Have a look at What is output buffering?, then http://www.php.net/manual/en/ref.outcontrol.php.

Related

How to echo php code and use it?

<?php echo $row["html"]; ?>
Inside of the $row["html"] there's:
<?php $Site->Nav($owner); ?>
but when I echo it, it only echoes:
Nav($owner); ?>
How may I print the full and make it usable, which means that it will print the function Nav?
I've tried to replace <?php with [[// i the database, and just before echoing it, I change back with replace. But without success
I think you need to use eval function of php. See the example below.
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
Might be it can help.
Use eval function. It might solve your problem like this:
<?php echo eval($row["html"]); ?>
Keep the code as is in DB as if you are writing it in PHP file but without PHP opening and closing tags i.e. <?php and ?>. I haven't checked this (as i am not sure what $Site->Nav($owner); will do) but hope it would work in this case.
If I understand correctly you are wanting to output the results of $Site->Nav($owner);
I have no idea what this is expected to output, but assuming it is a string of some kind that you wish to display (hence echo) - an example of achieving this would be calling your code and have that method return the value, so you can echo it out. Ie:
function Nav($owner){
// Do your stuff
return 'Your Desired Output';
}
Then on your page you would have
<?php echo $Site->Nav($owner); ?>
Which would echo "Your Desired Output".

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

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.

What's the solution for this kind of problem?

<a onclick="run('Hi, Tim! I&#039;ve got two', '">test</a>
The onclick event is not run at all.
The above is generated by something like this:
<a onclick="run(<?php echo htmlentities($str) ?>)">test</a>
How to fix it?
You are outputting the content of a string without quoting it
Put the echo statements in ''
<a onclick="run('<?php echo htmlentities($str) ?>')">test</a>
By the way, ' = '
$str, before being entity-encoded, is:
'Hi, Tim! I've got two', '
which is clearly not a valid JavaScript string literal. The apostrophe is HTML-encoded, which it shouldn't be yet, and there's some trailing nonsense.
You should create JavaScript string (and other) literals using the json_encode function. If you have $rawstr as:
Hi, Tim! I've got two
then json_encode will give you the correct JavaScript string:
'Hi, Tim! I\'ve got two'
so you can insert it into an HTML event handler attribute:
<a onclick="run(<?php echo htmlspecialchars(json_encode($rawstr)) ?>); return false;">test</a>
Note htmlspecialchars(), which is preferable to htmlentities(), as the latter will usually-needlessly HTML-escape all non-ASCII characters, which will mess them up if you don't specify the correct charset.
From PHP 5.3, you can use the JSON_HEX_ flags to ensure that the HTML-special characters are never in the output from json_encode, which saves you an encoding step:
<a onclick="run(<?php echo json_encode($rawstr, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT) ?>); return false;">test</a>
To make your life easier, encapsulate these common output-with-escaping methods into more simply-named functions:
function h($s) {
echo htmlspecialchars($s, ENT_QUOTES);
}
function j($s) {
echo json_encode($s, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT|JSON_HEX_APOS);
}
function u($s) {
echo urlencode($s);
}
<a onclick="run(<?php j($rawstr); ?>); return false;">test</a>
And even better, avoid using inline event handler attributes at all by binding from script:
<a id="test">test</a>
...
<script type="text/javascript">
document.getElementById('test').onclick= function() {
run(<?php j($rawstr); ?>);
return false;
};
</script>

Categories