Tencent Cloud Cloud Object Storage (COS) PHP SDK v5

repository·master·Indexed 41 days ago

https://github.com/tencentyun/cos-php-sdk-v5

Official PHP SDK for interacting with Tencent Cloud Cloud Object Storage (COS) via the XML API. It provides the Qcloud\Cos\Client for managing buckets and objects, featuring high-level helpers for uploading (up to 50TB via multipart), downloading, copying, and generating pre-signed URLs. Supports installation via Composer, Phar, or source, with compatibility for PHP >= 5.6.

Tokens
3.7K
Snippets
17
Records
18
Agent score
2%

What's inside COS PHP SDK

  1. Install COS-PHP-SDK-V5 via Phar or Source

    master

    Phar Installation

    1. Download the appropriate .phar file from the GitHub releases page.
      • For PHP >= 5.6 and < 7.2.5: Use cos-sdk-v5-6.phar (Guzzle 6).
      • For PHP >= 7.2.5: Use cos-sdk-v5-7.phar (Guzzle 7).
    2. Include it in your code:
    require '/path/to/cos-sdk-v5.phar';

    Source Installation

    1. Download the .tar.gz file from the GitHub releases page.
      • For PHP >= 5.6 and < 7.2.5: Use cos-sdk-v5-6.tar.gz (Guzzle 6).
      • For PHP >= 7.2.5: Use cos-sdk-v5-7.tar.gz (Guzzle 7).
    2. Unzip and include the autoloader:
    require '/path/to/cos-sdk-v5/vendor/autoload.php';
  2. Install COS-PHP-SDK-V5 via Composer

    master

    The recommended way to install the SDK is using Composer. This manages dependencies automatically and sets up an autoloader.

    1. Install Composer if you haven't already:
    curl -sS https://getcomposer.org/installer | php
    1. Create a composer.json file with the following content:
    {
        "require": {
            "qcloud/cos-sdk-v5": "2.*
        }
    }
    1. Run the installation command:
    php composer.phar install
    1. Include the autoloader in your PHP project:
    require '/path/to/vendor/autoload.php';
    composer require qcloud/cos-sdk-v5
  3. Initialize the Client with configuration

    master

    To use the COS SDK, instantiate the Qcloud\Cos\Client class by passing a configuration array. The configuration must include secretId and secretKey. You can also specify the region, scheme (http/https), and other connection settings.

    Key configuration options include:

    • scheme: Protocol to use (default: http).
    • region: The COS region (e.g., ap-guangzhou).
    • credentials: An array containing appId, secretId, secretKey, anonymous, and token.
    • timeout: Request timeout in seconds.
    • retry: Number of retry attempts for failed requests.
    • autoChange: If true, the client will automatically switch to tencentcos.cn or tencentci.cn endpoints if rate limiting is detected.
    use Qcloud//Cos\Client;
    
    $client = new Client([
        'region' => 'ap-guangzhou',
        'credentials' => [
            'secretId'  => 'YOUR_SECRET_ID',
            'secretKey' => 'YOUR_SECRET_KEY',
            'appId'     => 'YOUR_APP_ID',
        ],
    ]);
  4. Get a signed URL using getObjectUrl

    master

    Use getObjectUrl to generate a pre-signed URL for accessing a file. This is useful for providing temporary access to private files.

    // Generate a signed URL valid for 10 minutes
    try {
        $signedUrl = $cosClient->getObjectUrl($bucket, $key, '+10 minutes');
        echo $signedUrl;
    } catch (\Exception $e) {
        echo "$e\n";
    }
  5. Download files using getObject

    master

    Use getObject to retrieve files from COS. You can download the content into memory or save it directly to a local path using the SaveAs option. You can also specify a Range for partial downloads.

    // Download to memory
    $result = $cosClient->getObject(array(
        'Bucket' => $bucket,
        'Key' => $key
    ));
    echo $result['Body'];
    
    // Download to a local file
    $cosClient->getObject(array(
        'Bucket' => $bucket,
        'Key' => $key,
        'SaveAs' => $local_path
    ));
    
    // Download a specific range (e.g., first 11 bytes)
    $cosClient->getObject(array(
        'Bucket' => $bucket,
        'Key' => $key,
        'Range' => 'bytes=0-10',
        'SaveAs' => $local_path
    ));
  6. Upload files using Upload (Max 50TB)

    master

    The Upload method is an advanced interface that uses multipart upload by default, supporting files up to 50TB. It is suitable for large files.

    // Upload a string
    $result = $cosClient->Upload($bucket, $key, 'Hello World!');
    
    // Upload a file stream with options
    $result = $cosClient->Upload(
        $bucket,
        $key,
        fopen($local_path, 'rb'),
        array(
            'ACL' => 'string',
            'ContentType' => 'string',
            'Metadata' => array('key' => 'value')
        )
    );
  7. Upload files using putObject (Max 5GB)

    master

    The putObject method is used for simple uploads of files up to 5GB. You can upload strings directly or use a file stream.

    Note: The Bucket name must follow the format {name}-{appid}.

    // Upload a string
    $result = $cosClient->putObject(array(
        'Bucket' => $bucket,
        'Key' => $key,
        'Body' => 'Hello World!'
    ));
    
    // Upload a file stream
    $result = $cosClient->putObject(array(
        'Bucket' => $bucket,
        'Key' => $key,
        'Body' => fopen($local_path, 'rb')
    ));
  8. Initialize the Qcloud\Cos\Client

    master

    To use the SDK, you must instantiate a Qcloud\Cos\Client with your region and credentials.

    Standard Credentials: Use secretId and secretKey.

    Temporary Credentials: If using temporary security credentials, you must also provide the token (XCosSecurityToken).

    // Standard initialization
    $cosClient = new Qcloud\Cos\Client(array(
        'region' => '<Region>',
        'credentials' => array(
            'secretId' => '<SecretId>',
            'secretKey' => '<SecretKey>'
        )
    ));
    
    // Temporary credentials initialization
    $cosClient = new Qcloud\Cos\Client(array(
        'region' => '<Region>',
        'credentials' => array(
            'secretId' => '<SecretId>',
            'secretKey' => '<SecretKey>',
            'token' => '<XCosSecurityToken>'
        )
    ));
  9. Check if an object exists using doesObjectExist()

    master

    The doesObjectExist() method returns a boolean indicating whether a specific object exists at the given bucket and key. It wraps the HeadObject API call and catches exceptions to provide a simple true/false result.

    if ($client->doesObjectExist('my-bucket-name', 'path/to/my/object.txt')) {
        // Object exists
    }
  10. Download files using download()

    master

    The download() method is a high-level helper that handles downloading objects. For large files, it uses RangeDownload to perform a resumable download.

    Arguments:

    • $bucket: The name of the bucket.
    • $key: The object key.
    • $saveAs: The local path where the file should be saved.
    • $options: Array containing PartSize (default: RangeDownload::DEFAULT_PART_SIZE) and VersionId.
    $client->download('mybucket-12345678', 'test.txt', '/local/path/test.txt');
  11. Copy objects between buckets or regions using copy()

    master

    The copy() method allows you to copy an object from a source location to a destination bucket and key. It automatically determines whether to use a simple copyObject operation or a multi-part copy based on the object's size and the provided PartSize option.

    Parameters:

    • $bucket: The destination bucket name.
    • $key: The destination object key.
    • $copySource: An associative array containing the source details:
      • Bucket: Source bucket name.
      • Key: Source object key.
      • Region: Source region (e.g., ap-guangzhou).
      • VersionId: (Optional) The specific version of the object to copy.
    • $options: (Optional) Configuration options:
      • PartSize: The size threshold for multi-part copying. Defaults to Copy::DEFAULT_PART_SIZE.
    $client->copy(
        'destination-bucket-name',
        'destination-key',
        [
            'Bucket'   => 'source-bucket-name',
            'Key'      => 'source-key',
            'Region'   => 'ap-guangzhou',
            'VersionId' => 'some-version-id' // Optional
        ],
        ['PartSize' => 10485760] // Optional
    );
  12. Upload files using upload()

    master

    The upload() method is a high-level helper that automatically decides whether to use a simple putObject (for small files) or a MultipartUpload (for large files) based on the file size and the PartSize option.

    • Small files: Uploaded in a single request.
    • Large files: Automatically split into parts and uploaded using the multipart upload API.

    Arguments:

    • $bucket: The name of the bucket.
    • $key: The object key (path in bucket).
    • $body: The file content (string, resource, or PSR-7 stream).
    • $options: Array containing PartSize (default: MultipartUpload::DEFAULT_PART_SIZE) and other multipart options.
    $client->upload('mybucket-12345678', 'test.txt', '/path/to/local/file.txt');