Jump to content

dynamically change text within a php file


abdfahim

Recommended Posts

Guess u need that for a kind of config file. U cant change the variable's value directly but can use the file handling capabilities of php. In the example i used constants instead of variables. The code will change the value of 'John' to 'Harry' in constant 'NAME'.

 

config file:

<?php
constant('NAME', 'John');
constant('SURNAME', 'Smith');
?>

 

change config variables

<?php
$handle = fopen('config.php', 'w+');
$newValue = 'Harry';
while(!feof($handle)){
     $line = fgets($handle, 4096);
     if(strstr($line, "constant('NAME',")){
           $line = "constant('NAME', '{$newValue}');";
     }
     $output .= $line;
}
fwrite($handle, $output);
fclose($handle);
?>

 

Surely there may be a simpler method, but thats what i came with.

Hi, GuiltyGear .. first thing, I cant replace any line. I copy-paste ur code and it deletes whole contents of the config.php file, i.e. after running 2nd file, config.php becomes blank. I can't debug it because I never use file handling.

 

2nd thing is, can't I do something like

 

$var=urlencode("config.php")

and then changing $var? I don't want to rewrite main file because I guess it takes long time as I may have to rewrite that file many times. So if I can take the contents of the file in a variable and change the variable, I think that will be better. Is that possible?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.