9

I have:

<?php

$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");

if ($_POST["lastname"] <> "")
{
   fwrite($file,$_POST["lastname"]."\n");
}

fclose($file);

?>

but it overwrites the beginning of the file. How do I make it insert?

4 Answers 4

29

I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing file, or write new data to the start of an existing file, keeping the existing content after it?

To insert text without over-writing the beginning of the file, you'll have to open it for appending (a+ rather than r+)

$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");

if ($_POST["lastname"] <> "")
{
   fwrite($file,$_POST["lastname"]."\n");
}

fclose($file);

If you're trying to write to the start of the file, you'll have to read in the file contents (see file_get_contents) first, then write your new string followed by file contents to the output file.

$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);

The above approach will work with small files, but you may run into memory limits trying to read a large file in using file_get_conents. In this case, consider using rewind($file), which sets the file position indicator for handle to the beginning of the file stream. Note when using rewind(), not to open the file with the a (or a+) options, as:

If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.

5
  • 1
    You beat me to it I was writing this out.
    – UnkwnTech
    Sep 19, 2008 at 16:58
  • Well, isn't it overkill for large file ? I mean, file_get_contents copy all the file in memory, right. It's ok for an ini file, but for a log... In that case, a good all seek would do it, doesn't it ?
    – Bite code
    Sep 20, 2008 at 12:20
  • Good point, answer updated to mention rewind, avoiding reading the whole file into memory.
    – ConroyP
    Sep 20, 2008 at 22:20
  • Just bumped into this trying to solve a similar problem. Rewind (or fseek for that matter) is not a solution, as fopen with 'c' or 'r+' alway overwrites as many characters as the length of the string I want to write. Seems like it is actually not possible to insert a string in a file using php, all file size problems aside. Also see: stackoverflow.com/questions/17119677/…
    – MattiaG
    Sep 17, 2013 at 16:26
  • 1
    The last part of the answer is incorrect. The question is about inserting text, but if you use rewind, you are going to overwrite the content at the beginning of the file.
    – laurent
    Dec 5, 2013 at 9:17
1

A working example for inserting in the middle of a file stream without overwriting, and without having to load the whole thing into a variable/memory:

function finsert($handle, $string, $bufferSize = 16384) {
    $insertionPoint = ftell($handle);

    // Create a temp file to stream into
    $tempPath = tempnam(sys_get_temp_dir(), "file-chainer");
    $lastPartHandle = fopen($tempPath, "w+");

    // Read in everything from the insertion point and forward
    while (!feof($handle)) {
        fwrite($lastPartHandle, fread($handle, $bufferSize), $bufferSize);
    }

    // Rewind to the insertion point
    fseek($handle, $insertionPoint);

    // Rewind the temporary stream
    rewind($lastPartHandle);

    // Write back everything starting with the string to insert
    fwrite($handle, $string);
    while (!feof($lastPartHandle)) {
        fwrite($handle, fread($lastPartHandle, $bufferSize), $bufferSize);
    }

    // Close the last part handle and delete it
    fclose($lastPartHandle);
    unlink($tempPath);

    // Re-set pointer
    fseek($handle, $insertionPoint + strlen($string));
}

$handle = fopen("file.txt", "w+");
fwrite($handle, "foobar");
rewind($handle);
finsert($handle, "baz");

// File stream is now: bazfoobar

Composer lib for it can be found here

0

You get the same opening the file for appending

<?php
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
   fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
2
  • You probably should give some credit to this person stackoverflow.com/questions/103593/…
    – Chris
    Mar 30, 2018 at 1:26
  • 1
    @ChristofferHjärtström the issue is that I didn't use his response at all when I posted this almost 10 years ago and 11 min after the question was made Apr 3, 2018 at 19:32
0

If you want to put your text at the beginning of the file, you'd have to read the file contents first like:

<?php

$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");

if ($_POST["lastname"] <> "")
{    
    $existingText = file_get_contents($file);
    fwrite($file, $existingText . $_POST["lastname"]."\n");
}

fclose($file);

?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.