-1

I am trying to write in a configuration file, problem that it does not print $names

<?php 
    $myfile = fopen("config.php", "w") or die("Unable to open file!");
    $txt = "$dbname = '1'; $dbuser = '2'; $dbpass = '123'; $dbhost = 'localhost';\n"; 
    fwrite($myfile, $txt); 
    fclose($myfile);
?>

The output shows me

= '1';  = '1';  = '123';  = 'localhost';

I need he write the variables names, need some help, thanks!

Amit Verma
  • 8,660
  • 8
  • 35
  • 40

1 Answers1

0

You need to escape $ signs:

 $myfile = fopen("config.php", "w") or die("Unable to open file!"); 
 $txt = " \$dbname = '1'; \$dbuser = '2'; \$dbpass = '123'; \$dbhost = 'localhost';\n"; 
 fwrite($myfile, $txt); fclose($myfile);

Other wise use single quotes:

 $myfile = fopen("config.php", "w") or die("Unable to open file!"); 
 $txt = ' $dbname = "1"; $dbuser = "2"; $dbpass = "123"; $dbhost = "localhost";\n'; 
 fwrite($myfile, $txt); fclose($myfile);

Explanation:

variables $var in php are evaluated if in double quotes, but not in single quotes. I think that for performances it would always be better to avoid double quotes if the expression inside is constant and doesn't need to be evaluated.

koalaok
  • 5,075
  • 11
  • 47
  • 91