Reputation: 8836
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
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:
Also how can I add something on the end instead of the begining?
Use the append mode: "a".
Upvotes: 0
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