Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php method to read only part of remote file

I am working with file_get_contents getting remote files and processing them. Unfortunately the files are quite large and I only need a small segment from each. I know exactly from what offset I would need to read and the length of it but reading the php manual it seems that this is possible with file_get_contents only on local files.

Is there a method which doesn't download the whole file?

like image 563
slash197 Avatar asked Oct 04 '12 12:10

slash197


2 Answers

you need to use fopen, fseek and fread function instead of file_get contents

here are the links to the documentation of

  • fopen
  • fseek
  • fread

fopen opens the file as a stream of bytes and you can seek into your desired position using fseek and read as much byte as you need using fread

like image 119
haynar Avatar answered Sep 25 '22 03:09

haynar


As far as I know there is no way to open a remote file and move the file pointer to a certain point. You need some kind of remote service that provides that feature for you.

Although fopen and fseek seem to work, there is a cullpit. Form the manual:

Not all streams support seeking. For those that do not support seeking, forward seeking from the current position is accomplished by reading and discarding data; other forms of seeking will fail.

As for implementing a service, there a numerous example. I like the rsync solution, that mirrors only changed blocks from a remote to a local machine.

like image 34
JvdBerg Avatar answered Sep 21 '22 03:09

JvdBerg