Getting Started

Last updated: 2021-03-08 17:22:58

    Download and Installation

    • Download the source code for the COS XML PHP SDK here.
    • Download the XML PHP SDK here.
    • Download the PHP demo here.
    • For the complete sample code, please see SDK Sample Code.
    • For the SDK changelog, please see Changelog.

    Environmental dependencies

    • PHP 5.6+
      You can run the php -v command to view the current PHP version.

      Note:

      If your PHP version is >=5.3 and <5.6, please use v1.3.

    • cURL extension
      You can run the php -m command to check whether the cURL extension has been installed properly.
      • On Ubuntu, you can install PHP's cURL extension using the apt-get package manager with the following command:
        sudo apt-get install php-curl
      • On CentOS, you can install PHP's cURL extension using the yum package manager.
        sudo yum install php-curl

    Installing SDKs

    You can install the SDK using Composer, Phar, or the source code.

    Composer

    It is recommended to install cos-php-sdk-v5 with Composer, a PHP dependency manager that allows you to declare the dependencies necessary for your project and then automatically installs them into your project.

    Note:

    You can find more information such as how to install Composer, how to configure auto-load, and other best practices for defining dependencies at Composer official website.

    Installation steps

    1. Start the terminal.
    2. Download Composer and run the following command.
      curl -sS https://getcomposer.org/installer | php
    3. Create a file named composer.json with the following content:
      {
       "require": {
           "qcloud/cos-sdk-v5": ">=2.0"
       }
      }
    4. Run the following command to install the SDK with Composer.
      php composer.phar install
      This command will create a vendor folder in the current directory. The folder will contain the SDK's dependent library and an autoload.php script file for future calls in your project.
    5. Call cos-php-sdk-v5 with the autoloader script.
      require '/path/to/sdk/vendor/autoload.php';
      Now, you can use COS XML SDK for PHP in your project.

    Phar

    Install the SDK using the Phar method as instructed below:

    1. Download the phar file here.
    2. Import the phar file into your code.
    require  '/path/to/cos-sdk-v5.phar';

    Source code

    Install the SDK using the source code as instructed below:

    1. Download cos-sdk-v5.tar.gz compressed file on the SDK releases page.

      Note:

      Source code is packaged by GitHub by default. The vendor directory is not included.

    2. After decompressing it, load the SDK through the autoload.php script.
    require '/path/to/sdk/vendor/autoload.php';

    Getting Started

    The following describes how to use the PHP SDK of COS to perform basic operations, such as initializing the client, creating a bucket, querying the bucket list, uploading an object, querying the object list, downloading an object, and deleting an object. For more information about the parameters involved in the samples, please see Bucket Operations and Object Operations.

    Initialization

    $secretId = "COS_SECRETID"; //"TencentCloud API key's SecretId";
    $secretKey = "COS_SECRETKEY"; // "SecretKey of your Tencent Cloud API key";
    $region = "COS_REGION"; // Set the default bucket region
    $cosClient = new Qcloud\Cos\Client(
        array(
            'region' => $region,
            'schema' => 'https', // Protocol header; http by default
            'credentials'=> array(
                'secretId'  => $secretId ,
                'secretKey' => $secretKey)));

    If you initialize a client with a temporary key, create an instance in the following way.

    $tmpSecretId = "COS_SECRETID"; //"Temporary key's SecretId";
    $tmpSecretKey = "COS_SECRETKEY"; //"Temporary key's SecretKey";
    $tmpToken = "COS_TOKEN"; // "Token of the temporary key";
    $region = "COS_REGION"; // Set the default bucket region
    $cosClient = new Qcloud\Cos\Client(
        array(
            'region' => $region,
            'schema' => 'https', // Protocol header; http by default
            'credentials'=> array(
                'secretId'  => $tmpSecretId,
                'secretKey' => $tmpSecretKey,
                'token' => $tmpToken)));

    Creating a bucket

    try {
        $bucket = "examplebucket-1250000000"; // Bucket name in the format of BucketName-APPID
        $result = $cosClient->createBucket(array('Bucket' => $bucket));
        // Request successful
        print_r($result);
    } catch (\Exception $e) {
        // Request failed
        echo($e);
    }

    Querying the bucket list

    try {
        // Request successful
        $result = $cosClient->listBuckets();
        print_r($result);
    } catch (\Exception $e) {
        // Request failed
        echo($e);
    }

    Uploading an object

    Note:

    • Upload a file (up to 5 GB) using the putObject API.
    • Upload a file using the Upload API. The Upload API is a composition API that uses simple upload for small files and uses multipart upload for large files.
    • For the parameter description, please see Object Operations.
    # Upload a file
    ## putObject (an API that can upload files of up to 5 GB)
    ### Upload strings in memory
    try {
        $bucket = "examplebucket-1250000000"; // Bucket name in the format of BucketName-APPID
        $key = "exampleobject"; // Object key, the unique identifier of the object in the bucket
        $result = $cosClient->putObject(array(
            'Bucket' => $bucket,
            'Key' => $key,
            'Body' => 'Hello World!'));
        print_r($result);
    } catch (\Exception $e) {
        echo "$e\n";
    }
    
    ### Upload a file stream
    try {
        $bucket = "examplebucket-1250000000"; // Bucket name in the format of BucketName-APPID
        $key = "exampleobject"; // Object key, the unique identifier of the object in the bucket
        $srcPath = "path/to/localFile";// Absolute path to local file
        $file = fopen($srcPath, "rb");
        if ($file) {
            $result = $cosClient->putObject(array(
                'Bucket' => $bucket,
                'Key' => $key,
                'Body' => $file));
            print_r($result);
        }
    } catch (\Exception $e) {
        echo "$e\n";
    }
    
    ## Upload (advanced upload API, which can upload files of up to 50 TB with multipart upload)
    ### Upload strings in memory
    try {    
        $bucket = "examplebucket-1250000000"; // Bucket name in the format of BucketName-APPID
        $key = "exampleobject"; // Object key, the unique identifier of the object in the bucket
        $result = $cosClient->Upload(
            $bucket = $bucket,
            $key = $key,
            $body = 'Hello World!');
        print_r($result);
    } catch (\Exception $e) {
        echo "$e\n";
    }
    
    ### Upload a file stream
    try {    
        $bucket = "examplebucket-1250000000"; // Bucket name in the format of BucketName-APPID
        $key = "exampleobject"; // Object key, the unique identifier of the object in the bucket
        $srcPath = "path/to/localFile";// Absolute path to local file
        $file = fopen($srcPath, 'rb');
        if ($file) {
            $result = $cosClient->Upload(
                $bucket = $bucket,
                $key = $key,
                $body = $file);
        }
        print_r($result);
    } catch (\Exception $e) {
        echo "$e\n";
    }

    Querying the object list

    try {
        $bucket = "examplebucket-1250000000"; // Bucket name in the format of BucketName-APPID
        $result = $cosClient->listObjects(array(
            'Bucket' => $bucket
        ));
        // Request successful
        if (isset($result['Contents'])) {
            foreach ($result['Contents'] as $rt) {
                print_r($rt);
            }
        }
    } catch (\Exception $e) {
        // Request failed
        echo($e);
    }

    A single call to the listObjects API can query up to 1,000 objects. If you want to query all objects, you need to call it repeatedly.

    try {
        $bucket = "examplebucket-1250000000"; // Bucket name in the format of BucketName-APPID
        $prefix = ''; // Prefix of the objects to be listed
        $marker = ''; // End marker in the last list
        while (true) {
            $result = $cosClient->listObjects(array(
                'Bucket' => $bucket,
                'Marker' => $marker,
                'MaxKeys' => 1000 // Set the maximum number of entries to be listed in one single query, which is up to 1,000
            ));
            if (isset($result['Contents'])) {
                foreach ($result['Contents'] as $rt) {
                    // Print key
                    echo($rt['Key'] . "\n");
                }
            }
            $marker = $result['NextMarker']; // Set a new end marker
            if (!$result['IsTruncated']) {
                break; // Determine whether the query is complete
            }
        }
    } catch (\Exception $e) {
        echo($e);
    }

    Downloading an object

    • Download a file using the getObject API.
    • Get the file download URL using the getObjectUrl API.
    # Download a file
    ## getObject (download file)
    ### Download to memory
    try {
        $bucket = "examplebucket-1250000000"; // Bucket in the format of BucketName-APPID
        $key = "exampleobject";  // Object key, the unique identifier of the object in the bucket
        $result = $cosClient->getObject(array(
            'Bucket' => $bucket,
            'Key' => $key));
        // Request successful
        echo($result['Body']);
    } catch (\Exception $e) {
        // Request failed
        echo "$e\n";
    }
    
    ### Download to the local file system
    try {
        $bucket = "examplebucket-1250000000"; // Bucket in the format of BucketName-APPID
        $key = "exampleobject";  // Object key, the unique identifier of the object in the bucket
        $localPath = @"path/to/localFile";// Download to a specific local path
        $result = $cosClient->getObject(array(
            'Bucket' => $bucket,
            'Key' => $key,
            'SaveAs' => $localPath));
    } catch (\Exception $e) {
        // Request failed
        echo "$e\n";
    }
    
    ### Specify the download range
    /*
     * Range field is in the format of 'bytes=a-b'
     */
    try {
        $bucket = "examplebucket-1250000000"; // Bucket in the format of BucketName-APPID
        $key = "exampleobject";  // Object key, the unique identifier of the object in the bucket
        $localPath = @"path/to/localFile";// Download to a specific local path
        $result = $cosClient->getObject(array(
            'Bucket' => $bucket,
            'Key' => $key,
            'Range' => 'bytes=0-10',
            'SaveAs' => $localPath));
    } catch (\Exception $e) {
        // Request failed
        echo "$e\n";
    }
    
    ## getObjectUrl (get the file URL)
    try {    
        $bucket = "examplebucket-1250000000"; // Bucket in the format of BucketName-APPID
        $key = "exampleobject";  // Object key, the unique identifier of the object in the bucket
        $signedUrl = $cosClient->getObjectUrl($bucket, $key, '+10 minutes');
        // Request successful
        echo $signedUrl;
    } catch (\Exception $e) {
        // Request failed
        print_r($e);
    }

    Deleting an object

    # Delete an object
    ## deleteObject
    try {
        $bucket = "examplebucket-1250000000"; // Bucket in the format of BucketName-APPID
        $key = "exampleobject";  // Object key, the unique identifier of the object in the bucket
        $result = $cosClient->deleteObject(array(
            'Bucket' => $bucket,
            'Key' => $key,
            'VersionId' => 'string'
        ));
        // Request successful
        print_r($result);
    } catch (\Exception $e) {
        // Request failed
        echo($e);
    }
    # Delete multiple objects
    ## deleteObjects
    try {
        $bucket = "examplebucket-1250000000"; // Bucket in the format of BucketName-APPID
        $key1 = "exampleobject1";  // Object key, the unique identifier of the object in the bucket
        $key2 = "exampleobject2";  // Object key, the unique identifier of the object in the bucket
        $result = $cosClient->deleteObjects(array(
            'Bucket' => $bucket,
            'Objects' => array(
                array(
                    'Key' => $key1,
                ),
                array(
                    'Key' => $key2,
                ),
                //...
            ),
        ));
        // Request successful
        print_r($result);
    } catch (\Exception $e) {
        // Request failed
        echo($e);
    }

    Was this page helpful?

    Was this page helpful?

    • Not at all
    • Not very helpful
    • Somewhat helpful
    • Very helpful
    • Extremely helpful
    Send Feedback
    Help