EnexoOnoma
EnexoOnoma

Reputation: 8836

Small editing to my php code that adds a string at the beginning of files

The following code supposed to add at the beginning of my php files on the webserver the string abcdef.

However it replaces all the content with the abcdef. How can I correct it?

Also how can I add something on the end instead of the beginning?

foreach (glob("*.php") as $file) {

   $fh = fopen($file, 'c'); //Open file for writing, place pointer at start of file.
   fwrite($fh, 'abcdef');
   fclose($fh);

}

Upvotes: 0

Views: 56

Answers (2)

outis
outis

Reputation: 77420

However it replaces all the content with the abcdef. How can I correct it?

From the documentation for fopen on the "c" mode:

Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file.

When you write 'abcdef' to the file, it will overwrite the first six characters. To prepend text, you'll need to copy the existing content, either by reading it out before writing the additional text, or by:

  1. creating a new file,
  2. writing the new text,
  3. then copying over the old content,
  4. then removing the old file and
  5. renaming the new.

Also how can I add something on the end instead of the begining?

Use the append mode: "a".

Upvotes: 0

Eric Conner
Eric Conner

Reputation: 10762

You just need to open the file with a flag that allows you to write without truncating the file to zero length:

$fh = fopen($file, 'r+');

Upvotes: 1

Related Questions