Cannot print variable name in PHP file

Messages
89
Reaction score
0
Points
6
I want to save the following line in a file in PHP:
Code:
<?php $value=15; ?>

For this, I am using the following code:
Code:
$myFileHandle=fopen($myurl,'w');   // $myurl = URL of the file
$myData="<?php $value=".$value."; ?>"; // $value = 15
fwrite($myFileHandle,$myData);
fclose($myFileHandle);

But when I open the file, I find the following statement:
Code:
<?php 15=15; ?>

What am I doing wrong?

By the way, I am using WAMP server.
 
Last edited:

essellar

Community Advocate
Community Support
Messages
3,295
Reaction score
227
Points
63
When you use double quotes as a string delimiter, variables within the string are evaluated. With single quotes, you'd get a literal "$value" in $myData instead of the evaluated version. In double quotes, you need to escape the sigil:

PHP:
$myData="<?php \$value=".$value."; ?>"; // $value = 15
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
Note that if you're using double-quotes, you don't need to use the concatenation operator when combining data from a variable:
PHP:
$myData="<?php \$value=$value; ?>"; // $value = 15

Alternatively, if you use single quotes, you don't need to escape the dollar sign:
PHP:
$myData='<?php $value=' . (int) $value. '; ?>'; // $value = 15

All in all, you'd do well to read up on PHP string syntax.

Also, be wary of injection attacks. If the data comes from user input, filter it appropriately.
 
Last edited:
Top