### Install Composer Source: https://github.com/oracle/oci-php-sdk/blob/main/README.md This set of commands installs Composer, the dependency manager for PHP. It downloads the installer, runs it to create the `composer.phar` file, and then moves it to a global location for command-line access. This is essential for managing SDK dependencies. ```bash php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" php composer-setup.php php -r "unlink('composer-setup.php');" sudo mv composer.phar /usr/local/bin/composer ``` -------------------------------- ### Install OCI PHP SDK from Zip File using Composer Source: https://github.com/oracle/oci-php-sdk/blob/main/README.md This snippet demonstrates how to configure your `composer.json` file to consume the OCI PHP SDK from a local zip artifact. It includes specifying the artifact repository and the SDK version. Ensure the zip file is in the specified artifact directory. ```json { "name": "oracle/oci-php-sdk-consumer", "type": "project", "require": { "oracle/oci-php-sdk": "0.0.1" }, "repositories": [ { "type": "artifact", "url": "/path/to/artifacts" } ] } ``` -------------------------------- ### Install OCI PHP SDK from Git Repository using Composer Source: https://github.com/oracle/oci-php-sdk/blob/main/README.md This snippet shows how to configure your `composer.json` file to consume the OCI PHP SDK directly from a Git repository. It specifies a 'git' repository type and the branch to use. This method is useful for using the latest development versions. ```json { "name": "oracle/oci-php-sdk-consumer", "type": "project", "require": { "oracle/oci-php-sdk": "dev-master" }, "repositories": [ { "type": "git", "url": "https://github.com/organization/my-repo.git" } ] } ``` -------------------------------- ### Install PHP 8.0 on Oracle Linux 8 Source: https://github.com/oracle/oci-php-sdk/blob/main/README.md This command sequence installs PHP 8.0 on Oracle Linux 8 using the `dnf` package manager. It first lists available PHP modules and then installs the PHP 8.0 module group. This is a prerequisite for using the OCI PHP SDK. ```bash sudo dnf module list php sudo dnf install @php:8.0 -y ``` -------------------------------- ### Initialize and Use OCI PHP SDK Source: https://github.com/oracle/oci-php-sdk/blob/main/README.md This PHP code snippet demonstrates the basic usage of the OCI PHP SDK after installation. It includes requiring the Composer autoloader and using a common SDK class, `UserAgent`, to retrieve the user agent string. This serves as a simple test to confirm the SDK is integrated correctly. ```php ``` -------------------------------- ### Upload OCI Objects with PHP Source: https://context7.com/oracle/oci-php-sdk/llms.txt This example shows how to upload objects to an OCI bucket using the PHP SDK. It covers uploading both plain string content and file-based content, including setting metadata, content type, and MD5 verification for file uploads. Error handling for upload failures is also included. ```php getNamespace()->getJson(); $bucketName = 'my-application-bucket'; try { // Upload string content $response = $client->putObject([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'objectName' => 'documents/readme.txt', 'putObjectBody' => 'Hello from OCI Object Storage!', 'contentType' => 'text/plain', 'opcMeta' => [ 'author' => 'john-doe', 'department' => 'engineering', 'version' => '1.0' ] ]); echo "Object uploaded successfully\n"; echo "ETag: {$response->getHeaders()['ETag'][0]}\n"; echo "Request ID: {$response->getHeaders()['opc-request-id'][0]}\n"; // Upload file with MD5 verification $filePath = '/path/to/local/file.pdf'; $fileHandle = fopen($filePath, 'rb'); $response = $client->putObject([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'objectName' => 'uploads/report.pdf', 'putObjectBody' => $fileHandle, 'contentType' => 'application/pdf', 'contentMD5' => base64_encode(md5_file($filePath, true)), 'contentLength' => filesize($filePath), 'storageTier' => 'Standard', 'opcMeta' => [ 'upload-date' => date('Y-m-d H:i:s'), 'original-filename' => basename($filePath) ] ]); fclose($fileHandle); echo "File uploaded successfully\n"; } catch (Oracle\Oci\Common\OciBadResponseException $e) { echo "Upload failed: " . $e->getMessage() . "\n"; echo "Status: " . $e->getStatusCode() . "\n"; } ``` -------------------------------- ### Create and Configure an OCI Bucket Source: https://context7.com/oracle/oci-php-sdk/llms.txt Demonstrates how to create a new Object Storage bucket with specified configurations, including name, compartment ID, public access type, storage tier, versioning, and metadata. This operation requires an authenticated `ObjectStorageClient` and a valid compartment ID. Errors during creation are caught and reported. ```php getNamespace()->getJson(); $compartmentId = "ocid1.compartment.oc1..aaaaaaaexample"; try { // Create bucket $response = $client->createBucket([ 'namespaceName' => $namespace, 'createBucketDetails' => [ 'name' => 'my-application-bucket', 'compartmentId' => $compartmentId, 'publicAccessType' => 'NoPublicAccess', 'storageTier' => 'Standard', 'versioning' => 'Enabled', 'metadata' => [ 'environment' => 'production', 'owner' => 'team-data' ] ] ]); echo "Bucket created successfully\n"; $bucket = $response->getJson(); echo "Bucket name: {$bucket->name}\n"; echo "Created: {$bucket->timeCreated}\n"; } catch (Oracle\Oci\Common\OciBadResponseException $e) { echo "Error creating bucket: " . $e->getMessage() . "\n"; echo "Status code: " . $e->getStatusCode() . "\n"; } ``` -------------------------------- ### Simplify Object Storage Operations with PHP Helper Class Source: https://context7.com/oracle/oci-php-sdk/llms.txt Demonstrates using the ObjectStorageHelper class in PHP for simplified interaction with OCI Object Storage. This helper abstracts common operations, including listing objects, uploading files (with multipart upload configuration), and performing bulk deletions. It requires the OCI SDK for PHP and relies on authentication via ConfigFileAuthProvider. ```php [ 'partSize' => 20 * 1024 * 1024, // 20 MB parts 'allowMultipartUploads' => true, 'allowParallelUploads' => true ] ]); $namespace = $helper->getNamespace()->getJson(); $bucketName = 'my-application-bucket'; try { // All ObjectStorageClient methods available directly $response = $helper->listObjects([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'limit' => 100 ]); echo "Objects listed using helper\n"; // Upload manager methods available $uploadResponse = $helper->upload([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'objectName' => 'large-file.zip', 'uploadPartBody' => fopen('/path/to/large-file.zip', 'rb') ]); echo "File uploaded using upload manager\n"; // Bulk delete operations $deleteResponse = $helper->bulkDelete([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'objectNames' => ['file1.txt', 'file2.txt', 'file3.txt'] ]); echo "Bulk delete completed\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Authentication with Config File Source: https://context7.com/oracle/oci-php-sdk/llms.txt Initialize the ObjectStorageClient using credentials from the OCI config file, typically located at `~/.oci/config`. ```APIDOC ## Authentication with Config File ### Description Initialize the ObjectStorageClient using credentials from the OCI config file, typically located at `~/.oci/config`. ### Method Initialization ### Endpoint N/A ### Parameters N/A ### Request Example ```php getNamespace(); $namespace = $response->getJson(); echo "Connected to namespace: {$namespace}\n"; echo "Region: " . $auth_provider->getRegion() . "\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` ### Response #### Success Response - **namespace** (string) - The OCI namespace. - **region** (string) - The region the client is connected to. #### Response Example ```json { "namespace": "your_namespace_name", "region": "us-ashburn-1" } ``` ``` -------------------------------- ### POST /objectstorage/Bucket Source: https://context7.com/oracle/oci-php-sdk/llms.txt Create a new bucket with specific configuration options. ```APIDOC ## POST /objectstorage/Bucket ### Description Create a new bucket with specific configuration options such as name, compartment ID, public access type, storage tier, versioning, and metadata. ### Method POST ### Endpoint `/objectstorage/Bucket` ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **namespaceName** (string) - Required - The namespace for the bucket. - **createBucketDetails** (object) - Required - Details for creating the bucket. - **name** (string) - Required - The name of the bucket. - **compartmentId** (string) - Required - The OCID of the compartment to create the bucket in. - **publicAccessType** (string) - Optional - Specifies the public access type for the bucket. Possible values: `NoPublicAccess`, `ObjectRead`, `ObjectReadWithoutList`. - **storageTier** (string) - Optional - Specifies the storage tier for the bucket. Possible values: `Standard`, `Archive`. - **versioning** (string) - Optional - Specifies whether versioning is enabled for the bucket. Possible values: `Enabled`, `Disabled`. - **metadata** (object) - Optional - User-defined metadata for the bucket. ### Request Example ```php getNamespace()->getJson(); $compartmentId = "ocid1.compartment.oc1..aaaaaaaexample"; try { // Create bucket $response = $client->createBucket([ 'namespaceName' => $namespace, 'createBucketDetails' => [ 'name' => 'my-application-bucket', 'compartmentId' => $compartmentId, 'publicAccessType' => 'NoPublicAccess', 'storageTier' => 'Standard', 'versioning' => 'Enabled', 'metadata' => [ 'environment' => 'production', 'owner' => 'team-data' ] ] ]); echo "Bucket created successfully\n"; $bucket = $response->getJson(); echo "Bucket name: " . $bucket->name . "\n"; echo "Created: " . $bucket->timeCreated . "\n"; } catch (Oracle\Oci\Common\OciBadResponseException $e) { echo "Error creating bucket: " . $e->getMessage() . "\n"; echo "Status code: " . $e->getStatusCode() . "\n"; } ``` ### Response #### Success Response (200) - **name** (string) - The name of the bucket. - **namespace** (string) - The namespace the bucket belongs to. - **compartmentId** (string) - The OCID of the compartment the bucket belongs to. - **timeCreated** (string) - The date and time the bucket was created. - **etag** (string) - The etag for the bucket. - **metadata** (object) - User-defined metadata for the bucket. - **publicAccessType** (string) - The public access type of the bucket. - **storageTier** (string) - The storage tier of the bucket. - **versioning** (string) - The versioning state of the bucket. #### Response Example ```json { "name": "my-application-bucket", "namespace": "your_namespace_name", "compartmentId": "ocid1.compartment.oc1..aaaaaaaexample", "timeCreated": "2023-10-27T10:00:00.000Z", "etag": "some_etag_value", "metadata": { "environment": "production", "owner": "team-data" }, "publicAccessType": "NoPublicAccess", "storageTier": "Standard", "versioning": "Enabled" } ``` ``` -------------------------------- ### List and Manage OCI Buckets with PHP Source: https://context7.com/oracle/oci-php-sdk/llms.txt This snippet demonstrates how to list all buckets within a compartment, retrieve detailed information about a specific bucket, and check if a bucket exists using the OCI PHP SDK. It handles potential 'Not Found' errors and other exceptions. ```php getNamespace()->getJson(); $compartmentId = "ocid1.compartment.oc1..aaaaaaaexample"; try { // List all buckets with pagination $response = $client->listBuckets([ 'namespaceName' => $namespace, 'compartmentId' => $compartmentId, 'limit' => 100, 'fields' => ['tags', 'approximateSize', 'approximateCount'] ]); $buckets = $response->getJson(); echo "Found " . count($buckets) . " buckets\n"; foreach ($buckets as $bucket) { echo "Bucket: {$bucket->name}\n"; if (isset($bucket->approximateSize)) { echo " Size: {$bucket->approximateSize} bytes\n"; } if (isset($bucket->approximateCount)) { echo " Objects: {$bucket->approximateCount}\n"; } } // Get detailed bucket information $response = $client->getBucket([ 'namespaceName' => $namespace, 'bucketName' => 'my-application-bucket', 'fields' => ['approximateCount', 'approximateSize', 'autoTiering'] ]); $bucket = $response->getJson(); echo "\nBucket details:\n"; echo " ETag: {$response->getHeaders()['ETag'][0]}\n"; echo " Storage tier: {$bucket->storageTier}\n"; // Check if bucket exists $headResponse = $client->headBucket([ 'namespaceName' => $namespace, 'bucketName' => 'my-application-bucket' ]); echo "Bucket exists with ETag: {$headResponse->getHeaders()['ETag'][0]}\n"; } catch (Oracle\Oci\Common\OciBadResponseException $e) { if ($e->getStatusCode() == 404) { echo "Bucket not found\n"; } else { echo "Error: " . $e->getMessage() . "\n"; } } ``` -------------------------------- ### Authenticate OCI ObjectStorageClient with Config File Source: https://context7.com/oracle/oci-php-sdk/llms.txt Initializes the ObjectStorageClient using credentials from the `~/.oci/config` file. This is a common method for applications running outside of OCI compute instances. It requires the `vendor/autoload.php` to be included and uses `ConfigFileAuthProvider` for authentication. ```php getNamespace(); $namespace = $response->getJson(); echo "Connected to namespace: {$namespace}\n"; echo "Region: {$auth_provider->getRegion()}\n"; } catch (Exception $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Copy and Rename Objects using OCI PHP SDK Source: https://context7.com/oracle/oci-php-sdk/llms.txt This snippet demonstrates how to copy objects within or across regions and how to rename objects by performing a copy operation followed by a delete. It includes error handling and polls the work request status for completion. Dependencies include the OCI PHP SDK and an authenticated client instance. ```php getNamespace()->getJson(); $sourceBucket = 'source-bucket'; $destBucket = 'destination-bucket'; try { // Copy object within same region $response = $client->copyObject([ 'namespaceName' => $namespace, 'bucketName' => $sourceBucket, 'copyObjectDetails' => [ 'sourceObjectName' => 'original-file.pdf', 'destinationRegion' => $auth_provider->getRegion()->getRegionId(), 'destinationNamespace' => $namespace, 'destinationBucket' => $destBucket, 'destinationObjectName' => 'copied-file.pdf', 'destinationObjectMetadata' => [ 'copied-from' => 'original-file.pdf', 'copy-date' => date('Y-m-d') ] ] ]); $workRequestId = $response->getHeaders()['opc-work-request-id'][0]; echo "Copy operation initiated, work request: {$workRequestId}\n"; // Poll work request until complete $isComplete = false; while (!$isComplete) { $wrResponse = $client->getWorkRequest([ 'workRequestId' => $workRequestId ]); $workRequest = $wrResponse->getJson(); $status = $workRequest->status; echo "Copy status: {$status}\n"; if ($status == 'COMPLETED' || $workRequest->timeFinished != null) { $isComplete = true; echo "Copy completed at {$workRequest->timeFinished}\n"; } else { sleep(2); } } // Rename object (using copy + delete) $client->copyObject([ 'namespaceName' => $namespace, 'bucketName' => $sourceBucket, 'copyObjectDetails' => [ 'sourceObjectName' => 'old-name.txt', 'destinationRegion' => $auth_provider->getRegion()->getRegionId(), 'destinationNamespace' => $namespace, 'destinationBucket' => $sourceBucket, 'destinationObjectName' => 'new-name.txt' ] ]); // Wait for copy to complete, then delete original $client->deleteObject([ 'namespaceName' => $namespace, 'bucketName' => $sourceBucket, 'objectName' => 'old-name.txt' ]); echo "Object renamed successfully\n"; } catch (Oracle\Oci\Common\OciBadResponseException $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Create and Complete Multipart Upload in PHP Source: https://context7.com/oracle/oci-php-sdk/llms.txt This snippet demonstrates how to upload large files in parts using the `createMultipartUpload`, `uploadPart`, and `commitMultipartUpload` methods. It handles initiating the upload, uploading individual parts, and then completing the upload. Error handling includes aborting the multipart upload if an issue occurs. Dependencies include the OCI PHP SDK and file access. ```php getNamespace()->getJson(); $bucketName = 'my-application-bucket'; $objectName = 'large-files/video.mp4'; try { // Step 1: Initiate multipart upload $response = $client->createMultipartUpload([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'createMultipartUploadDetails' => [ 'object' => $objectName, 'contentType' => 'video/mp4', 'metadata' => [ 'description' => 'Training video', 'duration' => '00:15:30' ] ] ]); $uploadId = $response->getJson()->uploadId; echo "Multipart upload initiated: {$uploadId}\n"; // Step 2: Upload parts $filePath = '/path/to/large/video.mp4'; $partSize = 10 * 1024 * 1024; // 10 MB per part $fileHandle = fopen($filePath, 'rb'); $partNumber = 1; $parts = []; while (!feof($fileHandle)) { $partData = fread($fileHandle, $partSize); $response = $client->uploadPart([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'objectName' => $objectName, 'uploadId' => $uploadId, 'uploadPartNum' => $partNumber, 'uploadPartBody' => $partData, 'contentLength' => strlen($partData) ]); $etag = $response->getHeaders()['ETag'][0]; $parts[] = [ 'partNum' => $partNumber, 'etag' => $etag ]; echo "Uploaded part {$partNumber}, ETag: {$etag}\n"; $partNumber++; } fclose($fileHandle); // Step 3: Complete multipart upload $response = $client->commitMultipartUpload([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'objectName' => $objectName, 'uploadId' => $uploadId, 'commitMultipartUploadDetails' => [ 'partsToCommit' => $parts ] ]); echo "Multipart upload completed successfully\n"; echo "Final ETag: {$response->getHeaders()['ETag'][0]}\n"; } catch (Exception $e) { // Abort multipart upload on error if (isset($uploadId)) { $client->abortMultipartUpload([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'objectName' => $objectName, 'uploadId' => $uploadId ]); echo "Multipart upload aborted\n"; } echo "Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Create Pre-Authenticated Requests using OCI PHP SDK Source: https://context7.com/oracle/oci-php-sdk/llms.txt This snippet demonstrates creating pre-authenticated requests (PARs) for temporary, secure object access, including read and write operations. It shows how to generate URLs, list existing PARs, and delete them when no longer needed. Error handling is included. Dependencies: OCI PHP SDK, authenticated client instance. ```php getNamespace()->getJson(); $bucketName = 'my-application-bucket'; try { // Create PAR for object read access $response = $client->createPreauthenticatedRequest([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'createPreauthenticatedRequestDetails' => [ 'name' => 'temp-download-link', 'objectName' => 'documents/report.pdf', 'accessType' => 'ObjectRead', 'timeExpires' => date('c', strtotime('+1 hour')) ] ]); $par = $response->getJson(); $fullUrl = "https://objectstorage.{$auth_provider->getRegion()->getRegionId()}.oraclecloud.com" . $par->accessUri; echo "Pre-authenticated request created:\n"; echo " ID: {$par->id}\n"; echo " URL: {$fullUrl}\n"; echo " Expires: {$par->timeExpires}\n"; echo "\nShare this URL for temporary access (valid for 1 hour)\n"; // Create PAR for object write access $uploadPar = $client->createPreauthenticatedRequest([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'createPreauthenticatedRequestDetails' => [ 'name' => 'temp-upload-link', 'objectName' => 'uploads/new-file.txt', 'accessType' => 'ObjectWrite', 'timeExpires' => date('c', strtotime('+24 hours')) ] ]); echo "\nUpload URL created for external users\n"; // List all PARs $listResponse = $client->listPreauthenticatedRequests([ 'namespaceName' => $namespace, 'bucketName' => $bucketName ]); $pars = $listResponse->getJson(); echo "\nActive pre-authenticated requests: " . count($pars) . "\n"; // Delete PAR when no longer needed $client->deletePreauthenticatedRequest([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'parId' => $par->id ]); echo "PAR deleted successfully\n"; } catch (Oracle\Oci\Common\OciBadResponseException $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Download and Read Objects Source: https://context7.com/oracle/oci-php-sdk/llms.txt Retrieve object content and metadata, including support for partial content downloads and metadata retrieval without downloading the full object. ```APIDOC ## GET /n/{namespaceName}/b/{bucketName}/o/{objectName} ### Description Retrieves the content and metadata of a specific object within a bucket. Supports partial content retrieval using the 'range' parameter and fetching only metadata using the 'headObject' method. ### Method GET ### Endpoint `/n/{namespaceName}/b/{bucketName}/o/{objectName}` ### Parameters #### Path Parameters - **namespaceName** (string) - Required - The namespace of the bucket. - **bucketName** (string) - Required - The name of the bucket. - **objectName** (string) - Required - The name of the object to retrieve. #### Query Parameters - **range** (Oracle\Oci\Common\Range) - Optional - Specifies a byte range for partial content download (e.g., `new Oracle\Oci\Common\Range(0, 1023)` for the first 1KB). ### Request Body None ### Response #### Success Response (200 OK) - **body** (stream) - The object's content. - **headers** (object) - Object metadata, including: - **Content-Type** (string) - **Content-Length** (string) - **ETag** (string) - **opc-meta-* ** (string) - Custom metadata prefixed with 'opc-meta-'. #### Success Response (206 Partial Content) Returned when a 'range' query parameter is used. #### Error Response (404 Not Found) Returned if the object is not found. ### Request Example (PHP SDK) ```php $namespace = $client->getNamespace()->getJson(); $bucketName = 'my-application-bucket'; $objectName = 'documents/readme.txt'; // Download entire object $response = $client->getObject([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'objectName' => $objectName ]); $content = $response->getBody(); $headers = $response->getHeaders(); // Download with range request (partial content) $response = $client->getObject([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'objectName' => 'uploads/large-file.bin', 'range' => new Oracle\Oci\Common\Range(0, 1023) // First 1KB ]); // Get object metadata without downloading content $headResponse = $client->headObject([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'objectName' => $objectName ]); ``` ### Response Example (Success) ```json { "body": "This is the content of the readme.txt file.", "headers": { "Content-Type": ["text/plain"], "Content-Length": ["35"], "ETag": ["abcdef123456"], "Last-Modified": ["Tue, 15 Nov 1994 12:45:26 GMT"], "opc-meta-custom-key": ["custom-value"] } } ``` ``` -------------------------------- ### Authenticate OCI ObjectStorageClient with Instance Principals Source: https://context7.com/oracle/oci-php-sdk/llms.txt Authenticates the ObjectStorageClient for applications running on OCI compute instances using Instance Principals. This method does not require explicit credential configuration as it leverages the instance's metadata service. It uses `InstancePrincipalsAuthProvider` and can automatically refresh credentials. ```php getRegion(); echo "Instance region: {$region->getRegionId()}\n"; // Refresh credentials if needed (automatic on 401 errors) if ($auth_provider->isRefreshableOnNotAuthenticated()) { $auth_provider->refresh(); } } catch (Exception $e) { echo "Failed to authenticate with Instance Principals: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### List and Search OCI Objects with Filtering and Pagination (PHP) Source: https://context7.com/oracle/oci-php-sdk/llms.txt Lists objects within an OCI bucket, supporting filtering by prefix, specifying fields to retrieve, and handling pagination for large buckets. It also identifies common prefixes (folders). Requires the OCI PHP SDK and a configured client. ```php getNamespace()->getJson(); $bucketName = 'my-application-bucket'; try { // List all objects with prefix filter $response = $client->listObjects([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'prefix' => 'documents/', 'limit' => 100, 'fields' => 'name,size,timeCreated,md5', 'delimiter' => '/' ]); $listing = $response->getJson(); echo "Objects in bucket:\n"; if (isset($listing->objects)) { foreach ($listing->objects as $object) { echo " {$object->name} ({$object->size} bytes) - {$object->timeCreated}\n"; if (isset($object->md5)) { echo " MD5: {$object->md5}\n"; } } } // Handle prefixes (common prefixes/folders) if (isset($listing->prefixes) && count($listing->prefixes) > 0) { echo "\nFolders (prefixes):\n"; foreach ($listing->prefixes as $prefix) { echo " {$prefix}\n"; } } // Pagination through many objects $allObjects = []; $nextPage = null; do { $params = [ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'limit' => 1000 ]; if ($nextPage) { $params['start'] = $nextPage; } $response = $client->listObjects($params); $listing = $response->getJson(); if (isset($listing->objects)) { $allObjects = array_merge($allObjects, $listing->objects); } $nextPage = isset($listing->nextStartWith) ? $listing->nextStartWith : null; } while ($nextPage !== null); echo "\nTotal objects found: " . count($allObjects) . "\n"; } catch (Oracle\Oci\Common\OciBadResponseException $e) { echo "Error listing objects: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### List and Manage Multipart Uploads in PHP Source: https://context7.com/oracle/oci-php-sdk/llms.txt This snippet shows how to list and manage in-progress multipart uploads using the `listMultipartUploads` and `listMultipartUploadParts` methods. It allows monitoring of ongoing uploads, including their object names, upload IDs, creation times, and the number and details of uploaded parts. This is useful for tracking and debugging large file uploads. Dependencies include the OCI PHP SDK. ```php getNamespace()->getJson(); $bucketName = 'my-application-bucket'; try { // List all in-progress multipart uploads $response = $client->listMultipartUploads([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'limit' => 100 ]); $uploads = $response->getJson(); if (count($uploads) > 0) { echo "In-progress multipart uploads:\n"; foreach ($uploads as $upload) { echo " Object: {$upload->object}\n"; echo " Upload ID: {$upload->uploadId}\n"; echo " Started: {$upload->timeCreated}\n"; // List parts for specific upload $partsResponse = $client->listMultipartUploadParts([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'objectName' => $upload->object, 'uploadId' => $upload->uploadId, 'limit' => 1000 ]); $parts = $partsResponse->getJson(); echo " Parts uploaded: " . count($parts) . "\n"; foreach ($parts as $part) { echo " Part {$part->partNumber}: {$part->size} bytes, ETag: {$part->etag}\n"; } } } else { echo "No in-progress multipart uploads\n"; } } catch (Oracle\Oci\Common\OciBadResponseException $e) { echo "Error: " . $e->getMessage() . "\n"; } ``` -------------------------------- ### Authentication with Instance Principals Source: https://context7.com/oracle/oci-php-sdk/llms.txt Authenticate using the compute instance's principal for applications running on OCI compute instances. ```APIDOC ## Authentication with Instance Principals ### Description Authenticate using the compute instance's principal for applications running on OCI compute instances. This method does not require explicit credentials as it leverages the instance metadata service. ### Method Initialization ### Endpoint N/A ### Parameters N/A ### Request Example ```php getRegion(); echo "Instance region: " . $region->getRegionId() . "\n"; // Refresh credentials if needed (automatic on 401 errors) if ($auth_provider->isRefreshableOnNotAuthenticated()) { $auth_provider->refresh(); } } catch (Exception $e) { echo "Failed to authenticate with Instance Principals: " . $e->getMessage() . "\n"; } ``` ### Response #### Success Response - **regionId** (string) - The region ID of the compute instance. #### Response Example ```json { "regionId": "us-ashburn-1" } ``` ``` -------------------------------- ### Download and Read OCI Object Content and Metadata (PHP) Source: https://context7.com/oracle/oci-php-sdk/llms.txt Retrieves object content, headers, and custom metadata from OCI Object Storage. Supports full downloads, partial content via range requests, and fetching only metadata using headObject. Requires the OCI PHP SDK and a configured client. ```php getNamespace()->getJson(); $bucketName = 'my-application-bucket'; $objectName = 'documents/readme.txt'; try { // Download entire object $response = $client->getObject([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'objectName' => $objectName ]); $content = $response->getBody(); $headers = $response->getHeaders(); echo "Object content: {$content}\n"; echo "Content-Type: {$headers['Content-Type'][0]}\n"; echo "Content-Length: {$headers['Content-Length'][0]}\n"; echo "ETag: {$headers['ETag'][0]}\n"; // Access custom metadata foreach ($headers as $key => $value) { if (strpos($key, 'opc-meta-') === 0) { $metaKey = substr($key, 9); echo "Metadata {$metaKey}: {$value[0]}\n"; } } // Download with range request (partial content) $response = $client->getObject([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'objectName' => 'uploads/large-file.bin', 'range' => new Oracle\Oci\Common\Range(0, 1023) // First 1KB ]); echo "Downloaded {$response->getHeaders()['Content-Length'][0]} bytes\n"; // Get object metadata without downloading content $headResponse = $client->headObject([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'objectName' => $objectName ]); echo "Object size: {$headResponse->getHeaders()['Content-Length'][0]} bytes\n"; echo "Last modified: {$headResponse->getHeaders()['Last-Modified'][0]}\n"; } catch (Oracle\Oci\Common\OciBadResponseException $e) { if ($e->getStatusCode() == 404) { echo "Object not found\n"; } else { echo "Error: " . $e->getMessage() . "\n"; } } ``` -------------------------------- ### List and Search Objects Source: https://context7.com/oracle/oci-php-sdk/llms.txt List objects within a bucket, with support for filtering by prefix, limiting results, and paginating through large lists of objects. ```APIDOC ## GET /n/{namespaceName}/b/{bucketName}/o ### Description Lists objects within a specified bucket. Supports filtering by prefix, limiting the number of results, specifying the fields to return, and handling pagination for large result sets. Can also identify common prefixes (folders). ### Method GET ### Endpoint `/n/{namespaceName}/b/{bucketName}/o` ### Parameters #### Path Parameters - **namespaceName** (string) - Required - The namespace of the bucket. - **bucketName** (string) - Required - The name of the bucket. #### Query Parameters - **prefix** (string) - Optional - Filters results to objects that begin with this prefix. - **limit** (integer) - Optional - The maximum number of objects to return per page. Defaults to 1000. - **fields** (string) - Optional - A comma-separated list of fields to return for each object (e.g., 'name,size,timeCreated,md5'). - **delimiter** (string) - Optional - If set, results will contain objects and common prefixes under the specified delimiter (useful for simulating folders). - **start** (string) - Optional - The cursor to retrieve the next page of results. Used for pagination. ### Request Body None ### Response #### Success Response (200 OK) - **listing** (object) - Contains the list of objects and potentially common prefixes. - **objects** (array) - An array of object summary objects, each containing fields specified by the `fields` parameter. - **name** (string) - **size** (integer) - **timeCreated** (string - ISO 8601 format) - **md5** (string) - **prefixes** (array) - An array of common prefixes (folder names) if a delimiter is used. - **nextStartWith** (string) - A cursor for fetching the next page of results, if more results are available. #### Error Response - **message** (string) - Error message if the operation fails. ### Request Example (PHP SDK) ```php $namespace = $client->getNamespace()->getJson(); $bucketName = 'my-application-bucket'; // List objects with prefix filter and specific fields $response = $client->listObjects([ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'prefix' => 'documents/', 'limit' => 100, 'fields' => 'name,size,timeCreated,md5', 'delimiter' => '/' ]); $listing = $response->getJson(); // Pagination through many objects $allObjects = []; $nextPage = null; do { $params = [ 'namespaceName' => $namespace, 'bucketName' => $bucketName, 'limit' => 1000 ]; if ($nextPage) { $params['start'] = $nextPage; } $response = $client->listObjects($params); $listing = $response->getJson(); if (isset($listing->objects)) { $allObjects = array_merge($allObjects, $listing->objects); } $nextPage = isset($listing->nextStartWith) ? $listing->nextStartWith : null; } while ($nextPage !== null); ``` ### Response Example (Success) ```json { "objects": [ { "name": "documents/report.pdf", "size": 102400, "timeCreated": "2023-10-27T10:00:00Z", "md5": "a1b2c3d4e5f6..." }, { "name": "documents/image.jpg", "size": 51200, "timeCreated": "2023-10-27T10:05:00Z" } ], "prefixes": [ "documents/manuals/" ], "nextStartWith": "docu..." } ``` ```