Instead of using PHP's FTP extension (eg. ftp_get
), it is possible to open a stream using PHP's built-in FTP wrapper.
The following code would stream parts of an FTP-file to php://output
:
$start = 300; // First byte to stream
$stop = 499; // Last byte to stream
$url = "ftp://username:password@server.com/path/file.mp3";
$ctx = stream_context_create(array('ftp' => array('resume_pos' => $start)));
$fin = fopen($url, 'r', false, $ctx);
$fout = fopen('php://output', 'w');
stream_copy_to_stream($fin, $fout, $stop-$start+1);
fclose($fin);
fclose($fout);
While stream_copy_to_stream
has an $offset
parameter, using it resulted in an error because the stream was not seekable. Using the context option resume_pos
worked fine however.