Reputation: 10210
How to write in between content of existing file?
I tried to use fseek() to seek a new position and write the new content, but it replaces old content to the new string after seek position.
My aim is to put new contents after 5 characters of existing file.
Old content: AAAAABBBBB
, desired content: AAAAAnewcontentBBBBB
$file_handler = fopen('putty.log','w');
$new_content = 'this is new content';
fseek($file_handler,5);
echo ftell($file_handler); //5
fwrite($file_handler,$new_content);
old content replaced with NULLNULLNULLNULLNULLthis is new content
Upvotes: 1
Views: 624
Reputation: 1587
Writing in the middle of the file won't cause it to stretch and push the content forward (like when inserting content in a text editor) but rather to overwrite the content at the position you start writing. What you need to do is:
Example:
$original_file_name = '/tmp/putty.log';
$temp_file_name = '/tmp/putty.tmp';
$temp_file = fopen( $temp_file_name, 'w' );
$file_handler = fopen( $original_file_name, 'r' );
$old_data_size = 5;
fwrite( $temp_file, fread( $file_handler, $old_data_size ) );
$new_content = 'this is new content';
fwrite( $temp_file, $new_content, strlen( $new_content ) );
fwrite( $temp_file, fread( $file_handler, filesize( $original_file_name ) - $old_data_size ) );
fclose( $file_handler );
fclose( $temp_file );
unlink( $original_file_name );
rename( $temp_file_name, $original_file_name );
Make sure that putty.log has read/write permissions for the user used by your webserver (apache/lighttpd etc.) process or that it's accessible for everyone (not recommended).
Upvotes: 1
Reputation: 6848
if you're using fseek() to write data to a file, remember to open the file in "r+" mode, example:
$fp=fopen($filename,"r+");
Upvotes: 1
Reputation: 12925
You can't do it that way.
You can only truncate the content with ftruncate and write later the old content
A not so clean example
<?php
$file_handler = fopen('putty.log','rb+');
$new_content = 'this is new content';
fseek($file_handler,5);
$restOfContent = fread($file_handler,filesize('putty.log')-5);
ftruncate($file_handler,5);
fseek($file_handler,5);
echo ftell($file_handler); //5
fwrite($file_handler,$new_content);
fwrite($file_handler,$restOfContent);
fclose($file_handler)
Upvotes: 1
Reputation: 16616
Upvotes: 1