Jump to content

Question about editing php files


me102

Recommended Posts

Hello I have the following code from php websites

$myfile = fopen("/config.php", "a+") or die("Unable to open file!");

while(!feof($myfile)) {
  echo fgets($myfile) . "<br>";
 
  $txt = "Mickey Mouse\n";
  fwrite($myfile, $txt);
}

inside config.php is

<?php  
  define('script_path', 'files');
?>

How can I replace files with another value? any help would be great thanks.

Link to comment
https://forums.phpfreaks.com/topic/292697-question-about-editing-php-files/
Share on other sites


<?php
$my_file = "/config.php";
if (file_exists($my_file)) {
   
    /*
    //adds a new line
   
    $write = fopen($my_file, 'a+');
    //rewind($write);//append to top
    $message = "Mickey Mouse\r\n";
    fputs($write, $message);
    fclose($write);
   
    */
   
    //note the w, this will overwrite the entire contents
    $write   = fopen($my_file, 'w');
    $message = "Mickey Mouse\r\n";
    fputs($write, $message);
    fclose($write);
   
} else {
echo "$my_file doesn't exist";
}
?>

Best way would be to edit the config.php yourself.

 

But of want to PHP to do the edit for you then you'd need to loop over each line in the file. Find the line that defines that constant and then replace that line with the new value. Example

<?php
// the file to edit
$config_file = 'config.php';

// the new value for the script_path constant
$new_script_path_value = 'NEW/PATH/HERE';

// open the config file using file(). Strip the new lines from each line
// each line will be separate item in the $lines array
$lines = file($config_file, FILE_IGNORE_NEW_LINES);

// loop over each line
foreach($lines as $k => $line)
{
    // find the line that defines the 'script_path' constant
    if(strpos($line, "define('script_path'") !== false)
    {
        // replace the constant with the new  value
        $lines[$k] = "define('script_path', '$new_script_path_value');";
        
        // use break to to exist the foreach loop. 
        // No longer need to continue looping through the lines to find the constant as we have found it
        break;
    }
}

// implode the lines back into a string with newlines
$file_contents = implode(PHP_EOL, $lines);

// write the contents of the file back to the config file
file_put_contents($config_file, $file_contents);

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.