harsimarriar96
harsimarriar96

Reputation: 323

How to make variables work in Single Quotes properly?

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

Upvotes: 0

Views: 70

Answers (3)

Kyle Emmanuel
Kyle Emmanuel

Reputation: 2221

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

Upvotes: 2

datagutten
datagutten

Reputation: 163

If you use double quotes it works:

$handle = fopen('../config.php', 'w');
fwrite($handle, "
<?php
$connection = mysql_connect({$host}, {$user}, {$pass});
?>
");
fclose($handle);

Upvotes: 1

Quentin
Quentin

Reputation: 943556

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.

Upvotes: 4

Related Questions