简体   繁体   中英

php file_put_content overwrite

So i found this code which lets be write to a specific line

  function SetSiteName(){
        global $session, $database, $form;
    $filepathname = "include/classes/constants.php";
    $target = 'sitename';
    $newline = 'define("sitename", "Testing.");';

    $stats = file($filepathname, FILE_IGNORE_NEW_LINES);   
    $offset = array_search($target,$stats) +32;
    array_splice($stats, $offset, 0, $newline);   
    file_put_contents($filepathname, join("\n", $stats)); 
    header("Location: ".$session->referrer);
   }

however it will not overwrite whats on that line it'll go to the next line and put the data in.. I'd like to make it overwrite what currently is on that line?

Any thoughts?

You can overwrite a line of a file with this code.

$filename = "file.txt";
$content = file_get_contents($filename);
$lines_array = explode(PHP_EOL, $content);

//overwrite the line that you want.
$lines_array[5] = "New text at line 6!";

file_put_contents($filename, implode(PHP_EOL, $lines_array));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM