In order to interact with this feature, you must first retrieve a particular container using its unique name:
$container = $service->getContainer('{containerName}');
There are three ways to upload a new file, each of which has different business needs.
Note
Unlike previous versions, you do not need to manually specify your object's content type. The API will do this for you.
Note
When working with names that contain non-standard alphanumerical characters (such as spaces or non-English characters), you must ensure they are encoded with urlencode before passing them in.
The simplest way to upload a local object, without additional metadata, is by its path:
$container->uploadObject('example.txt', fopen('/path/to/file.txt', 'r+'));
The resource handle will be automatically closed by Guzzle in its destructor,
so there is no need to execute fclose
.
Get the executable PHP script for this example
Although the previous section handles most use cases, there are times when you want greater control over what is being uploaded. For example, you might want to control the object's metadata, or supply additional HTTP headers to coerce browsers to handle the download a certain way. To add metadata to a new object:
use OpenCloud\ObjectStore\Resource\DataObject;
// specify optional metadata
$metadata = array(
'Author' => 'Camera Obscura',
'Origin' => 'Glasgow',
);
// specify optional HTTP headers
$httpHeaders = array(
'Content-Type' => 'application/json',
);
// merge the two
$allHeaders = array_merge(DataObject::stockHeaders($metadata), $httpHeaders);
// upload as usual
$container->uploadObject('example.txt', fopen('/path/to/file.txt', 'r+'), $allHeaders);
As you will notice, the first argument to uploadObject
is the remote object
name, i.e. the name it will be uploaded as. The second argument is either a
file handle resource, or a string representation of object content (a temporary
resource will be created in memory), and the third is an array of additional
headers.
Get the executable PHP script for this example
$files = array(
array(
'name' => 'apache.log',
'path' => '/etc/httpd/logs/error_log'
),
array(
'name' => 'mysql.log',
'body' => fopen('/tmp/mysql.log', 'r+')
),
array(
'name' => 'to_do_list.txt',
'body' => 'PHONE HOME'
)
);
$container->uploadObjects($files);
As you can see, the name
key is required for every file. You must
also specify either a path key (to an existing file), or a body
.
The body
can either be a PHP resource or a string representation of
the content you want to upload.
Get the executable PHP script for this example
For files over 5GB, you will need to use the
OpenCloud\ObjectStore\Upload\TransferBuilder
factory to build and execute your
transfer. For your convenience, the Container resource object contains a simple
method to do this heavy lifting for you:
$transfer = $container->setupObjectTransfer(array(
'name' => 'video.mov',
'path' => '/home/user/video.mov',
'metadata' => array('Author' => 'Jamie'),
'concurrency' => 4,
'partSize' => 1.5 * Size::GB
));
$transfer->upload();
You can specify how many concurrent cURL connections are used to upload parts of your file. The file is fragmented into chunks, each of which is uploaded individually as a separate file (the filename of each part will indicate that it's a segment rather than the full file). After all parts are uploaded, a manifestfile is uploaded. When the end-user accesses the 5GB by its true filename, it actually references the manifest file which concatenates each segment into a streaming download.
In Swift terminology, the name for this process is Dynamic Large Object (DLO). To find out more details, please consult the official documentation.
Get the executable PHP script for this example
To return a list of objects:
$files = $container->objectList();
foreach ($files as $file) {
/** @var $file OpenCloud\ObjectStore\Resource\DataObject */
}
By default, 10,000 objects are returned as a maximum. To get around this, you can construct a query which refines your result set. For a full specification of query parameters relating to collection filtering, see the official docs.
$container->objectList(array('prefix' => 'logFile_'));
Get the executable PHP script for this example
To retrieve more than 10,000 objects (the default limit), you'll need to use the built-in paging which uses a 'marker' parameter to fetch the next page of data.
$containerObjects = array();
$marker = '';
while ($marker !== null) {
$params = array(
'marker' => $marker,
);
$objects = $container->objectList($params);
$total = $objects->count();
$count = 0;
if ($total == 0) {
break;
}
foreach ($objects as $object) {
/** @var $object OpenCloud\ObjectStore\Resource\DataObject **/
$containerObjects[] = $object->getName();
$count++;
$marker = ($count == $total) ? $object->getName() : null;
}
}
Get the executable PHP script for this example
To retrieve a specific file from Cloud Files:
/** @var $file OpenCloud\ObjectStore\Resource\DataObject */
$file = $container->getObject('summer_vacation.mp4');
Once you have access to this OpenCloud\ObjectStore\Resource\DataObject
object, you can access these attributes:
/** @param $container OpenCloud\ObjectStore\Resource\Container */
$container = $object->getContainer();
/** @param $name string */
$name = $object->getName();
/** @param $size int */
$size = $object->getContentLength();
/** @param $content Guzzle\Http\EntityBody */
$content = $object->getContent();
/** @param $type string */
$type = $object->getContentType();
/** @param $etag string */
$etag = $object->getEtag();
/** @param $lastModified string */
$lastModified = $object->getLastModified();
You can also perform conditional requests according to RFC 2616
specification (§§ 14.24-26).
Supported headers are If-Match
, If-None-Match
,
If-Modified-Since
and If-Unmodified-Since
.
So, to retrieve a file's contents only if it's been recently changed
$file = $container->getObject('error_log.txt', array(
'If-Modified-Since' => 'Tue, 15 Nov 1994 08:12:31 GMT'
));
if ($file->getContentLength()) {
echo 'Has been changed since the above date';
} else {
echo 'Has not been changed';
}
Retrieve a file only if it has NOT been modified (and expect a 412 on failure):
use Guzzle\Http\Exception\ClientErrorResponseException;
try {
$oldImmutableFile = $container->getObject('payroll_2001.xlsx', array(
'If-Unmodified-Since' => 'Mon, 31 Dec 2001 23:00:00 GMT'
));
} catch (ClientErrorResponseException $e) {
echo 'This file has been modified...';
}
Finally, you can specify a range - which will return a subset of bytes from the file specified. To return the last 20B of a file:
$snippet = $container->getObject('output.log', array('range' => 'bytes=-20'));
$file->setContent(fopen('/path/to/new/content', 'r+'));
$file->update();
Bear in mind that updating a file name will result in a new file being generated (under the new name). You will need to delete the old file.
To copy a file to another location, you need to specify a string-based destination path:
$object->copy('/container_2/new_object_name');
Where container_2
is the name of the container, and new_object_name
is
the name of the object inside the container that does not exist yet.
Get the executable PHP script for this example
To create a symlink to this file in another location you need to specify a string-based source
$object->createSymlinkFrom('/container_2/new_object_name');
Where container_2
is the name of the container, and new_object_name
is
the name of the object inside the container that either does not exist yet or
is an empty file.
Get the executable PHP script for this example
To set this file to symlink to another location you need to specify a string-based destination
$object->createSymlinkTo('/container_2/new_object_name');
Where container_2
is the name of the container, and new_object_name
is
the name of the object inside the container.
The object must be an empty file.
Get the executable PHP script for this example
You can fetch just the object metadata without fetching the full content:
$container->getPartialObject('summer_vacation.mp4');
In order to access the metadata on a partial or complete object, use:
$object->getMetadata();
You can turn a partial object into a full object to get the content after looking at the metadata:
$object->refresh();
You can also update to get the latest metadata:
$object->retrieveMetadata();
Get the executable PHP script for this example
Similarly, with setting metadata there are two options: you can update the metadata values of the local object (i.e. no HTTP request) if you anticipate you'll be executing one soon (an update operation for example):
// There's no need to execute a HTTP request, because we'll soon do one anyway for the update operation
$object->setMetadata(array(
'Author' => 'Hemingway'
));
// ... code here
$object->update();
Alternatively, you can update the API straight away - so that everything is retained:
$object->saveMetadata(array(
'Author' => 'Hemingway'
));
Please be aware that these methods override and wipe existing values. If you want to append values to your metadata, use the correct method:
$metadata = $object->appendToMetadata(array(
'Author' => 'Hemingway'
));
$object->saveMetadata($metadata);
Get the executable PHP script for this example
CloudFiles provides you the ability to extract uploaded archives to particular destinations. The archive will be extracted and its contents will populate the particular area specified. To upload file (which might represent a directory structure) into a particular container:
use OpenCloud\ObjectStore\Constants\UrlType;
$service->bulkExtract('container_1', fopen('/home/jamie/files.tar.gz','r'), UrlType::TAR_GZ);
You can also omit the container name (i.e. provide an empty string as the first argument). If you do this, the API will create the containers necessary to house the extracted files - this is done based on the filenames inside the archive.
Get the executable PHP script for this example
$container->deleteObject('{objectName}');
Get the executable PHP script for this example
$object->delete();
Get the executable PHP script for this example
Bulk delete a set of paths:
$pathsToBeDeleted = array('/container_1/old_file', '/container_2/notes.txt', '/container_1/older_file.log');
$service->batchDelete($pathsToBeDeleted);
Get the executable PHP script for this example
To check whether an object exists:
/** @var bool $exists */
$exists = $container->objectExists('{objectName}');