Installation guide
}
// Be sure to close the stream resource when you're done with it
fclose($stream);
}
Opening Seekable streams
Streams opened in "r" mode only allow data to be read from the stream, and are not seekable by default. This is so
that data can be downloaded from Amazon S3 in a truly streaming manner where previously read bytes do not need
to be buffered into memory. If you need a stream to be seekable, you can pass seekable into the stream context
options of a function.
$context = stream_context_create(array(
's3' => array(
'seekable' => true
)
));
if ($stream = fopen('s3://bucket/key', 'r', false, $context)) {
// Read bytes from the stream
fread($stream, 1024);
// Seek back to the beginning of the stream
fseek($steam, 0);
// Read the same bytes that were previously read
fread($stream, 1024);
fclose($stream);
}
Opening seekable streams allows you to seek only to bytes that were previously read. You cannot skip ahead to
bytes that have not yet been read from the remote server. In order to allow previously read data to recalled, data is
buffered in a PHP temp stream using Guzzle's CachingEntityBody decorator. When the amount of cached data
exceed 2MB, the data in the temp stream will transfer from memory to disk. Keep this in mind when downloading
large files from Amazon S3 using the seekable stream context setting.
Uploading data
Data can be uploaded to Amazon S3 using file_put_contents().
file_put_contents('s3://bucket/key', 'Hello!');
You can upload larger files by streaming data using fopen() and a "w", "x", or "a" stream access mode. The
Amazon S3 stream wrapper does not support simultaneous read and write streams (e.g. "r+", "w+", etc). This is
because the HTTP protocol does not allow simultaneous reading and writing.
$stream = fopen('s3://bucket/key', 'w');
fwrite($stream, 'Hello!');
fclose($stream);
Note
Because Amazon S3 requires a Content-Length header to be specified before the payload of a request is sent,
the data to be uploaded in a PutObject operation is internally buffered using a PHP temp stream until the stream
is flushed or closed.
fopen modes
Amazon S3 Stream Wrapper
132