0

I want those variables to be filled with their values, but in config.php file its writing the variable name itself, I want like $host convert to 'localhost' with single quotes in the config.php file.

    $handle = fopen('../config.php', 'w');
    fwrite($handle, '
    <?php
    $connection = mysql_connect({$host}, {$user}, {$pass});
    ?>
    ');
    fclose($handle);
tshepang
  • 12,111
  • 21
  • 91
  • 136
harsimarriar96
  • 313
  • 2
  • 11
  • 2
    You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). – Quentin Jul 19 '14 at 15:04
  • Its just a project for my institute, I didn't learn mysqli or pdo yet. – harsimarriar96 Jul 19 '14 at 15:11

3 Answers3

4

You can't. Single quotes do not interpolate variables. It the major thing that distinguishes them from double quotes. Use double quotes (or something else, such as sprintf) instead.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I want to write the config.php file can you help me how can I write it? with the variables printing. – harsimarriar96 Jul 19 '14 at 15:04
  • @harsimarriar96 Quentin has answered you're question, you're on the right lines so go and have a go at doing it yourself. If you have any further questions: create a new question. – David Barker Jul 19 '14 at 15:11
2

If you use variables within single quotes, they will be represented as strings instead of variables.

You can also do it like this:

// Get from $_SESSION (if started)
$host = $_SESSION['host'];
$user = $_SESSION['user'];
$pass = $_SESSION['pass'];

$handle = fopen('../config.php', 'w');

// try with the {}
$content = '<?php $connection = mysql_connect('."{$host},"."{$user},"."{$pass});".'?>';

// or you can try this too, but comment out the other one:
$content = '<?php $connection = mysql_connect('."\"$host\","."\"$user\","."\"$pass\");".'?>';

fwrite($handle, $content);
fclose($handle);
Kyle Emmanuel
  • 2,193
  • 1
  • 15
  • 22
1

If you use double quotes it works:

$handle = fopen('../config.php', 'w');
fwrite($handle, "
<?php
$connection = mysql_connect({$host}, {$user}, {$pass});
?>
");
fclose($handle);
datagutten
  • 163
  • 1
  • 9
  • When I try to double quotes, It reads the $connection variable too, I want it to read only $host, $user, $pass and the rest should be written as it is. – harsimarriar96 Jul 19 '14 at 15:10
  • Put a \ in front of $connection to escape it to avoid php reading it as a variable. – datagutten Jul 19 '14 at 15:17