Jump to content

Recommended Posts

hi, im using the following code to read the content of a file, and then add a line to the end of the file.

 

$file = dirname(dirname(dirname(__FILE__))).'/includes/settings.php';
$read = fopen($file, 'r')or die('Opening Error');

$content = fread($read, filesize($file));

fclose($read)or die('Close Error'); 

if(isset($_POST['cat_bg']))
{
    $write = fopen($file, 'w')or die('Opening Error');
    
    $cat_bg = $_POST['cat_bg'];

    $new_content = $content.'$color[\'cat_header\'][\'background\'] = '.$cat_bg.';';

    fwrite($write, $new_content)or die('Write Error');
    
    fclose($write);
}

 

however i would like to delete a line from the file before the content in inserted as the new line i am inserting is a duplicate variable with a different value.

 

Can anyone help?

 

Link to comment
https://forums.phpfreaks.com/topic/235698-replace-line-in-file/
Share on other sites

It maybe easier to read the file into an array, then concatenate it back to a string for example

<?php
$myfile = 'myFile.txt';
$lines = file($myfile);
if(isset($_GET['Remove'])){
   //remove line
   unset($lines[$_GET['Remove']]);
   //save file
   file_put_contents($myfile, implode("/n",$lines));
}
if(isset($_GET['add'])){
   //add line
   $lines[] = "this is a new line";
   //save file
   file_put_contents($myfile, implode("/n",$lines));
}

//display file
foreach ($lines as $line_num => $line) {
    echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "[<a href='?Remove={$line_num}'>Remove</a>]  [<a href='?add=true'>Add</a>]<br />\n";
}

 

Edit: fixed a typo

EDIT: just added  "add line" your get what i mean

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.