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.

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.