PHP Function Reference

PHP stream_copy_to_stream() Function



The PHP stream_copy_to_stream() function copies data from one stream to another. It copies up to length bytes of data from the current position (or from the offset position, if specified) from one stream to another. If length is null, all remaining content will be copied.

Syntax

stream_copy_to_stream(from, to, length, offset)

Parameters

from Required. Specify the source stream.
to Required. Specify the destination stream.
length Optional. Specify the maximum bytes to copy. By default all bytes left will be copied.
offset Optional. Specify the offset where to start to copy data. Default is 0.

Return Value

Returns the total count of bytes copied, or false on failure.

Example: stream_copy_to_stream() example

ThLets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, the stream_copy_to_stream() function is used to copy first 25 bytes of this file into part1.txt and remaining in part2.txt.

<?php
//opening the source file for reading
$src = fopen("test.txt", "r");

//creating destination files
$dest1 = fopen("part1.txt", "w");
$dest2 = fopen("part2.txt", "w");

echo stream_copy_to_stream($src, $dest1, 25) . " bytes copied to part1.txt\n";
echo stream_copy_to_stream($src, $dest2) . " bytes copied to part2.txt\n";

//closing all files
fclose($src);
fclose($dest1);
fclose($dest2);

//reading and displaying the content of the file
echo "\npart1.txt contains:\n";
echo file_get_contents("part1.txt");
echo "\n\npart2.txt contains:\n";
echo file_get_contents("part2.txt");
?>

The output of the above code will be:

25 bytes copied to part1.txt
23 bytes copied to part2.txt

part1.txt contains:
This is a test file.
It 

part2.txt contains:
contains dummy content.

❮ PHP Streams Reference