PDA

View Full Version : Writing to a file. (PHP)


Nasimov
04-13-2004, 08:15 AM
It's possible to ammend data within a file vs. just adding data to the beginning or the end of the file? Mean to change something in the "middle" of the file.

Thanks.

Charter
04-13-2004, 08:38 AM
Hi. Here's one way to do it.

<?php

$filename = "filename.ext";
$oldtext = "old text";
$newtext = "new text";

if (is_writable($filename)) {
$buffer = implode("", file($filename));
$buffer = str_replace($oldtext, $newtext, $buffer);
$handle = fopen($filename, "wb");
fwrite($handle, $buffer);
fclose($handle);
}
else {
clearstatcache();
echo "Cannot write to ".$filename." - Check permissions.";
}

?>