how to write variables value with file_put_contents()? - php

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

Related

Run PHP code stored in a database

database has php value saved like that as string
<?php $s = 'my name is'; ?>
and what am trying to do is calling the value as php code and want when type echo $s; to print my name is but now it's given my empty value see the code below to get what i mean
<?php
$b = '<?php $s = 'my name is';?>';
echo $b; //empty value
?>
Sounds like you're talking about eval() - but I'd be wary of using it. If you do, be extremely careful.
"If eval() is the answer, you're almost certainly asking the wrong question." -Rasmus Lerdorf
You'd probably need to strip the <?php and ?> tags, and watch for double quotes surrounding variables you don't want to replace:
$s=0;
eval('$s = "my name is";');
echo $s;
PHP is not recursively embeddable:
$b = '<?php $s = 'my name is';?>';
That's not PHP code in there. it's some text with the letters <, ?, p, etc...
And you ARE getting output. But you're viewing it in a browser, so the <?php ... ?> gets rendered as an unknown/illegal html tag and simply not displayed. If you'd bothered doing even the most basic of debugging, e.g. "view source", you'd have seen your PHP "code" there.

php echo a hyperlink with javascript confirm function

I have been using this code for deleting data from database. What i wan is whenever a user clicks an image link to delete data from the confirm function prompts up and ask for action, i am getting error in this code.
$delurl = "delete_dish.php?dish_id=".$row['id'];
$img = "<img src = 'images/delete.png'>";
echo "<a href=".$delurl.";
echo "onclick='return confirm('Are you sure you want to delete.')'>".$img."</a>";
Maybe the error is in double quotes or single quotes, Any help
Thanks in advance
change
echo "<a href=".$delurl.";
to
echo "<a href=\"".$delurl."\" ";
$delurl = "delete_dish.php?dish_id=".$row['id'];
$img = "<img src = 'images/delete.png'>";
$confirm_box <<<CONFIRM
<a href="$delurl"
onclick="return confirm('Are you sure you want to delete?')">$img</a>
CONFIRM;
// then elsewhere ...
echo $confirm_box
Always tend towards using the HEREDOC syntax to construct HTML/JS output, it will save you a lot of heartache. Just watch out for the major gotcha, DO NOT INDENT THE FIRST/LAST lines of the heredoc declaration.
EDIT The benefit being that you can mix single and double quotes as much as you like, you only have to worry about the JS quoting - PHP variables are interpolated without the quotes. You can further wrap curly quotes around your PHP variables like {$this} to make it easier to read, but also to delineate $this and {$this}tle.
I would us the following instead of escaping, this is more readable to me:
$delurl = "delete_dish.php?dish_id=".$row['id'];
$img = "<img src = 'images/delete.png'>";
?>
<?=$img?>
You can, may and should escape when handling stuff like this:
echo "<a href=\".$delurl.\"";
echo " onclick=\"return confirm('Are you sure you want to delete.')\">".$img."</a>";
lg,
flo

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

php echo doesnt print newlines

I started doing a new project in PHP / MySql . The Aim of this project is to manage articles for a magazine that i am the editor of.
So the content of the articles, i decided i would store with the "TEXT" column type of MySql
Now when i retrieve this column and print it with echo, the newlines are not there. Its all on the same line.
$resset = mysql_query("select txt from articles where id = 1");
$row = mysql_fetch_assoc($resset);
$txt = $row['txt'];
echo $txt; //doesnt print it as it is in the database as it was typed (multiline)
Find below, the text as it looks in the database and as it looks when it is echoed
in the databse, it is with new lines http://img413.imageshack.us/img413/4195/localhostlocalhostzxcvb.jpg
Text as it looks when echod http://img718.imageshack.us/img718/1700/sdashboardmozillafirefo.jpg
But within the database, its stored with newlines.
Has anybody else encountered this problem?
Please help me as my project depends on this :|
Whitespace in HTML is folded into a single space. Use nl2br() if you want to maintain newlines in HTML.
Have you tried
echo $txt."<br/>";
alternatively, you can put your output between <pre> tags:
echo "<pre>";
$resset = mysql_query("select txt from articles where id = 1");
$row = mysql_fetch_assoc($resset);
$txt = $row['txt'];
echo $txt; //doesnt print it as it is in the database as it was typed (multiline)
echo "</pre>";
btw,
echo $txt."<br/>";
may not work since it will just append newline at the end but not within $txt string
I know this isn't part of your question, but if you additionally want new lines in your HTML code but not your presentation, use double quotes with \n. This can help keep the HTML really tidy.
echo "\n";

Categories