Miscellaneous ⇒ User & Newbie Resources ⇒ PHP how to insert data into a specific file position ⇒ Community Forums ⇒ CPG Dragonfly™ CMS
Forum IndexUser & Newbie Resources

PHP how to insert data into a specific file position Reply to topic


I had to insert data into a file at a specified position while shifting down the remaining written data. Not an everyday thing, but may be handy in some circumstances.

fwrite will overwrite the data, instead of shifting it.

even if you fopen a file with append mode and move the pointer at the beginning, it will still append the data at the end of the file.

No luck yet and PHP offers no functions for what I need to do.

There are other ways to do that but they all use fread; fpassthru, instead, is incrementally faster as the file gets bigger.

I then wrote a little function, customized to my needs, but the basics are here.
<?php
function finsert($res, array &$data) {
	# position, in bytes, where the pointer is located
	$at = ftell($res);
	# create an empty buffer
	ob_start();
	# save to buffer all data from $at to EOF, basically what needs to be shifted
	fpassthru($res);
	# move buffer to variable
	$lower = ob_get_clean();
	# fpassthru move the pointer to EOF so we need to go back
	fseek($res, $at);
	# finally write data right after $at
	$data['length'] = fwrite($res, $data['stream']);
	# custom
	$data['end'] = ftell($res);
	# append the saved buffer to file
	fwrite($res, $lower);
}
?>


Notes:
*Make sure you don't fopen with append mode.
*Prior using this function you must fseek to the point where the data have to be insterted at.

Hope it helps.

.:: I met php the 03 December 2003 :: Unforgettable day! ::.

Server specs (Server OS / Apache / MySQL / PHP / DragonflyCMS):
CloudLinux / Apache 2.4 LSAPI / MySQLi 5.6 / PHP 5.6 / DCVS


usage example

<?php
$data = array('stream' = "Hello world\n");
$res = fopen($file, 'x+b');
# write lock
stream_set_file_buffer($res, 0);
# search for the $offset unless you know that already
fseek($res, $offset);
finsert($res, $data);
fclose($res);

# echoes 12
echo $data['length'];

# echoes the last end byte written with $data['stream'], good to know in case you need further processing.
echo $data['end'];
?>


Cheers

Server specs (Server OS / Apache / MySQL / PHP / DragonflyCMS):
none available


Exactly, but, as a side note just to make it clear to everyone, if you don't know the $offset and you use fread to scan the file then you wont need to fseek Wink

.:: I met php the 03 December 2003 :: Unforgettable day! ::.

Server specs (Server OS / Apache / MySQL / PHP / DragonflyCMS):
CloudLinux / Apache 2.4 LSAPI / MySQLi 5.6 / PHP 5.6 / DCVS

All times are UTC


Jump to: