Jump to content

Recommended Posts

Hello everyone.

I am currently working on a little project.

Now I tried to make a php config editor, but without success.

I simply can not get it to work...

 

This Is what i want to do.

I have a file, named file.php

<?php
//Some
//comments
$flower = "red";
$case = "black";
$done = "0";
//end of config file
?>

 

Now I need a function which does the following:

1.) Open the specific file (file.php)

2.) Search for the var $flower

3.) Change its value to "green"

 

So the file will look like:

<?php
//Some
//comments
$flower = "green";
$case = "black";
$done = "0";
//end of config file
?>

 

I tried it with fopen(), fread() and fclose(), but since the function does not know what is the value of $flower at the beginning, I did not get it to work.

Can someone help me out?

Link to comment
https://forums.phpfreaks.com/topic/164739-solved-php-config-editor/
Share on other sites

No I am looking for what i described in my first post

 

Now I need a function which does the following:

1.) Open the specific file (file.php)

2.) Search for the var $flower

3.) Change its value to "green"

 

(Please also see my examples for some further explanation)

I fixed it using:

 

<?php
function set_var($file,$var,$val)
{
$array = file("$file",FILE_IGNORE_NEW_LINES); 
$lines = count($array); 
for($i=1; $i<$lines-1; $i=$i+1) 
{
$line = $array[$i];
	if ($line[0] == "$") 
	{
                list($var_tmp, $val_tmp) = explode("=", $line);
	$variabele = substr($var_tmp, 1, -1);  
                  	if ($var == $variabele) { $array[$i] = "$var_tmp= \"$val\";"; }
	}
}
$fh = fopen($file, 'w') or die("Could not update config.php");
$stringData = "<?php\n";
fwrite($fh, $stringData);
$lines = count($array);
for($i=1; $i<$lines-1; $i=$i+1) 
{
$line = $array[$i];
fwrite($fh,"$line\n");
}
$stringData = "?>";
fwrite($fh, $stringData);
fclose($fh);
}
?>

 

This will do exactly what I asked in my first post.

But its a huge pile of code, and I am sure it can be done way faster.

Can anyone give some suggestions on how to optimize this code?

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.