EnexoOnoma
EnexoOnoma

Reputation: 8834

How to write a string at the beginning of txt files massively?

I have 100 txt files on my webserver. I have to insert a string e.g. abcdef on the beginning of all of them using php and save them back again. How is this possible ?

Upvotes: 2

Views: 98

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191799

Look at opendir, glob, fopen, and fwrite. For example:

foreach (glob("*.txt") as $file) {
   $fh = fopen($file, 'c'); //Open file for writing, place pointer at start of file.
   fwrite($fh, 'abcdef');
   fclose($fh);
}

Upvotes: 0

orlp
orlp

Reputation: 117791

Well, google found this.

function prepend($string, $filename) {
    $context = stream_context_create();
    $tmpname = tempnam(".");

    $fp = fopen($filename, "r", 1, $context);
    file_put_contents($tmpname, $string);
    file_put_contents($tmpname, $fp, FILE_APPEND);
    fclose($fp);

    unlink($filename);
    rename($tmpname, $filename);
}

So you call prepend($string, $filename) for every file and you're done.

Upvotes: 3

Related Questions