Mike M
Mike M

Reputation: 103

Replacing the variables in a file read by php

I have a small app I am working on that generates configuration files. Because it may be used to generate a few different variants of configurations, I gather the variable values from the user, and then read in a template configuration from a file. That file has the names of the variables in it (i.e. $ip_address) at the proper positions. I have set those variables in my php code before reading and the printing out the files. However, the variable names are printed out, not the values of the variables:

$hostname = $_POST['username'] . "_891";
$domain = $_POST['username'] . ".local";   
$routerFile = "891.txt";

$file_handle = fopen($routerFile, "r");
while (!feof($file_handle)) {
   $line = fgets($file_handle);
   print $line . "<br />";
}

Output example:

hostname $hostname
ip domain-name $domain

How do I get php to replace the variables names with their stored values?

Upvotes: 0

Views: 2428

Answers (3)

alex
alex

Reputation: 490163

You could use eval(), but that's not very safe, so I'd write a super simple regex replace.

$replaced = preg_replace_callback("/\b$\w+\b/", 
                                  function($match) use $hostname, $domain { 
                                      return $$match
                                  },
                                  $line);

However, I'd place the terms that need to be replaced inside of an associative array, otherwise your list of use will become a nightmare.

If you really want those files to be treated as PHP files and there is no security risk with them (they didn't come from an untrusted source) just include them.

Upvotes: 2

shadyyx
shadyyx

Reputation: 16055

I would go this way:

Create a template with hostname = <?php echo $hostname; ?> lines like so:

hostname <?php echo $hostname; ?>
ip domain-name <?php echo $domain; ?>

Then in PHP creating a template You would do:

ob_start();
include_once($routerFile);
$file_output = ob_get_clean();

Now You have the file template filled with the appropriate variables and You can save that file:

file_put_contents('my_new_router_file.txt', $file_output);

And You should be done.

Upvotes: 2

JvdBerg
JvdBerg

Reputation: 21856

I second alex answer. Another possibility is to ditch the txt file, replace it with a php file and just include that.

Upvotes: 0

Related Questions