Bart Scheffer
Bart Scheffer

Reputation: 507

How to echo a variable that's not a variable yet

I'm struggling with the following script:

$filename = '../lang.nl.php'; 
$string   = '<?php // language = ' . $filename . '<br>'; 

foreach ($_POST as $param_name => $param_val) {
    $string .= "$lang=['". $param_name ."'] = ". $param_val .";\n"; 
}

$string .= "?>";
file_put_contents($filename, $string); 

As you can see I want to create a language file with all the $_POST variables but PHP sees the $lang in $string as a variable. You can imagine that this is not what I want, it should just print $lang not whatever $lang as a variable should be. I get the error that $lang doesn't exist but I just want to literally print $lang.

Upvotes: 0

Views: 44

Answers (2)

georg
georg

Reputation: 215009

It's easier (and safer) to use var_export here:

$filename = '../lang.nl.php'; 
$post = var_export($_POST, true);
$code = "<?php // language = $filename;
    \$lang = $post;
?>";
file_put_contents($filename, $code);

"$lang=['". $param_name ."'] = ". $param_val; is going to fail if param_val contains a quote.

Upvotes: 1

Bob Brown
Bob Brown

Reputation: 1502

Escape the $: $string .= "\$lang=['". $param_name ."'] = ". $param_val .";\n";

What is different from the original code is the backslash before $lang, which makes the $ sign an ordinary $ sign and not a marker for a variable name.

Upvotes: 2

Related Questions