Jump to content

fwrite() question


bachx

Recommended Posts

You have to open the file usnig append, I think. I wrote this a while ago it uses fseek to move around the pointer.

function insertInFile($file, $string, $loc)
{
$wfile = fopen($file, "r+");
if (!$wfile)
	return false;
rewind($wfile);
fseek($wfile, $loc, SEEK_SET);
$endstring = fread($wfile, (filesize($file)-$loc));
fseek($wfile, $loc, SEEK_SET);
fwrite($wfile, $string . $endstring);
fclose($wfile);
}

You will have to modify it to replace existing text.

Link to comment
https://forums.phpfreaks.com/topic/66563-fwrite-question/#findComment-333392
Share on other sites

This is how I have updated a text file which replaces the whole file with what you enter

 

<?
$fund = file_get_contents($myFile);
$myFile = "../includes/thermometer/testFile.txt";
$name = $_POST['fund']; // vars from form
if (!isset($_POST['fund'])) {

?>	
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
    <p style="margin-left:10px;">The current fund is:<br>
    <input type="text" title="Please enter the new current fund amount" name="fund" size="30" value="<? echo $fund ?>">
</form>
<?}

else {
    $fund=$_REQUEST['fund'];
?>

<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
    <p style="margin-left:10px;">The current fund is:<br />
    <input type="text" title="Please enter the new current fund amount" name="fund" size="30" value="<? echo $fund; ?>">
</form>

<?
    $fh = fopen($myFile, 'w') or die("can't open file");
    $stringData = $name;
    fwrite($fh, $stringData);
    fclose($fh);
}
?>

Link to comment
https://forums.phpfreaks.com/topic/66563-fwrite-question/#findComment-333791
Share on other sites

Like I said, you will have to modify my function to make it replace text instead of insert it. In order to replace the text, all you need to know is that length of the text you are replacing, then start the "$endstring" that many characters farther. Or a very simple method, as otuatail suggested, is to just read the entire file into a buffer, modify it, and overwrite the entire file with it.

Link to comment
https://forums.phpfreaks.com/topic/66563-fwrite-question/#findComment-335307
Share on other sites

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.