Printing varchar php variable inside the javascript function - php

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.

Related

Echo javascript with a php function inside?

Oh boy! I cant get this to work. Any ideas on what the heck I'm doing wrong? Here's the code.
I'm trying to echo the script but use a php function to get the directory of the js file!!
Any help would be appreicated!!
echo '<script src="<?php get_some_function();?> . /js/main.js"></script>';
I've tried dif scenerios with escaping but cant get this to output correctly.
Since you're already in the PHP context, you can simply concatenate the strings, like so:
echo '<script src="' . get_some_function() . '/js/main.js"></script>';
Using sprintf() looks more cleaner, though:
echo sprintf('<script src="%s/js/main.js"></script>', get_some_function());
Instead of opening another script tag inside the string, concat the string and echo. The <?php within your string will not be evaluated.
echo '<script src="'. get_some_function() . '/js/main.js"></script>';
Simple string concatenation:
echo '<script src="' . get_some_function() . '/js/main.js"></script>';
Don't forget to properly escape the output of your function!
try doing this:
echo '<script src="'.get_some_function().' /js/main.js"></script>';
or this:
$value = get_some_function();
echo '<script src="'.$value.' /js/main.js"></script>';
Remember that any variable echoed in single quotes ( ' ' ), the value of that variable will be not printed, and if a variable is echoed in double quotes ( " " ) it will be printed.
Similar is true for returned data from a function stored in a varaible. If you are using single quotes, then every php code (variable, or a method call of a class) should be concatenated using dot operator ( . , :P ) . If you are using double quotes, then no need to use . .
Like in all above answers, they have used . to append the php function call, your code may be fine as below also (not tested by me, so you will need to do adjustment) :
$src = get_some_function();
echo "<script src=$src/js/main.js></script>";
But please note that it is a best practice to use single quotes for any kind of html etc echoed in php code, because HTML attributes are using double quotes.
Hope this will help...

Returning print_r as a string (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.

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 write variables value with file_put_contents()?

Have been trying to figure this out all day assuming its just a small error.....
I'm trying to use the file_put_content to put a variables value into another php file..
Code below will explain:
File that writes the data into the php:
<?php
require ('conf_2135432135435135412312534.php');
$F_name =$_POST['F__name'];
$L_name =$_POST['L__name'];
$E_mail =$_POST['Email'];
$GDI_user =$_POST['GDIusername'];
$ip=$_SERVER['REMOTE_ADDR'];
$C_date = date("F j, Y, g:i a");
mysql_connect($hostname,$username,$password) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$sql = "INSERT INTO $usertable (F_name, L_name, Email, GDI_username, Registration_IP, Date_registered) VALUES ('$F_name', '$L_name', '$E_mail', '$GDI_user', '$ip', '$C_date')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
$get_id = mysql_query("SELECT * FROM $usertable WHERE ". "GDI_username = '$GDI_user'");
while($id_check = mysql_fetch_array($get_id)) {
$UNQ_ID = $id_check["Unique_id"];
}
$src = "/home/files/1/741/html/WP/Default_files";
$dest = "/home/files/1/741/html/WP/$GDI_user";
echo "$GDI_user/config.php";
shell_exec("cp -r $src $dest");
file_put_contents("/home/files/1/741/html/WP/$GDI_user/config.php",'<?
$affiliate_reference = "$UNQ_ID";
echo $UNQ_ID;
?>');
?>
^^Short explanation of what that code does:^^
1.) Takes info from a html form
2.) INSERTS the data into a DB
3.) Fetches a Unique_id number from the DB
4.) Makes a copy of a folder with all the contents in it (Default_files)
5.) The duplicate folder is given a name of what was entered into the HTML form
6.) Writes into a file contained in the duplicate folder (config.php)
What the output (config.php) SHOULD contain:
<?
$affiliate_reference = "2154216354154"; //<<<thats just an example number
echo 2154216354154;
?>
Instead, This is what's showing up:
<?
$affiliate_reference = "$UNQ_ID";
echo $UNQ_ID;
?>
completely lost here. Any help would be much appreciated.
You're using ' to define the string, this means that the value will be left unparsed. The trick here, though, is that you want $UNQ_ID parsed, but you want $affiliate_reference left as is. This means you have to escape or manually concatenate
I would use this instead:
'<?
$affiliate_reference = "'.$UNQ_ID.'";
echo '.$UNQ_ID.';
?>'
Notice, I am using the single quote for the majority of the string. This is purposeful, you don't want the $affiliate_reference to be output. You only want $UNQ_ID turned into its string equivalent. Your other option is to use " and escape the $:
"<?
\$affiliate_reference = "'.$UNQ_ID.'";
echo '.$UNQ_ID.';
?>"
Note the \ to escape $ in front of $affiliate_reference.
I generally prefer the first way, color syntax highlighters will make that very obvious (even notice how SO handles it), while the second example causes highlighters to glaze over the whole thing. It is a preference, but it is an important one.
Of course, there is always the silly:
$a = '$';
followed by
"<?
${a}affiliate_reference = "'.$UNQ_ID.'";
echo '.$UNQ_ID.';
?>"
Use that only with people you don't like.
Change the single quotes surrounding the string you are writing to the file to doubles quotes. So:
file_put_contents("/home/files/1/741/html/WP/$GDI_user/config.php",'<?
$affiliate_reference = "$UNQ_ID";
echo $UNQ_ID;
?>');
...becomes...
file_put_contents("/home/files/1/741/html/WP/$GDI_user/config.php","<?php\n\n $affiliate_reference = '$UNQ_ID';\n echo $UNQ_ID;\n\n?>");
A couple of thoughts on this operation
Don't use PHP short tags - use <?php instead of <? as short tags are not supported everwhere and are disabled by default on new PHP installations
Don't put new-line literals in the middle of quoted strings, use HEREDOC syntax if you want to do that. It's best to avoid this if possible as it can lead to cross-platform compatibility issues. Use \r, \n, \r\n and the PHP_EOL constant instead.
Read this thoroughly so you know exactly what you can and can't do, and where.
The problem is that you are using single quotes, so the variables are not shown.
Change:
file_put_contents("/home/files/1/741/html/WP/$GDI_user/config.php",'<?
$affiliate_reference = "$UNQ_ID";
echo $UNQ_ID;
?>');
to:
file_put_contents("/home/files/1/741/html/WP/$GDI_user/config.php","<?
$affiliate_reference = '$UNQ_ID';
echo $UNQ_ID;
?>");
Note that I have changed the double quotes for $affiliate_reference to single quotes. If you need double quotes, you can escape them:
$affiliate_reference = \"$UNQ_ID\";
There are a few things wrong with this code. First, to address your problem, single quotes do not expand variables. That is the difference between single quotes and double.
After cursory inspection, I would recommend the following additional changes:
1) Sanitize your input prior to inserting into the database, you can use mysql_real_escape_string for this.
2) Use copy inside of a function that recurses the directory in order to copy it. This allows proper error handling. At a minimum, sanitize $GDI_user (via basename or some other method to prevent ..)
You're using single quotes. You cannot embed variable's values into a single-quoted string. Use concatenation, double-quotes, or heredoc.
http://php.net/string
And I think leading zeros in a number might cause problems, but I'm not sure. Plus it's always safe to use addslashes in situations like this.
$escaped_UNQ_ID = addslashes($UNQ_ID);
file_put_contents("/home/files/1/741/html/WP/$GDI_user/config.php", "<?php
\$affiliate_reference = \"$escaped_UNQ_ID\";
echo \$affiliate_reference;
?>");

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