GithubHelp home page GithubHelp logo

cos-php-sdk-v5's Introduction

COS-PHP-SDK-V5

腾讯云 COS-PHP-SDK-V5(XML API

PHP Version License Latest Stable Version Total Downloads Build Status codecov Support Multiple Versions

依赖

  • PHP >= 5.6

如果您的 php 版本 >=5.3<5.6 , 请使用 v1.3 版本

  • ext-curl
  • ext-json
  • ext-simplexml
  • ext-mbstring

安装

SDK 安装有三种方式:

Composer 方式

推荐使用 Composer 安装 cos-php-sdk-v5,Composer 是 PHP 的依赖管理工具,允许您声明项目所需的依赖,然后自动将它们安装到您的项目中。

composer require qcloud/cos-sdk-v5

您可以在 Composer 官网 上找到更多关于如何安装 Composer,配置自动加载以及用于定义依赖项的其他最佳实践等相关信息。

安装步骤

  1. 打开终端;
  2. 下载 Composer,执行以下命令:
curl -sS https://getcomposer.org/installer | php
  1. 创建一个名为composer.json的文件,内容如下:
{
    "require": {
        "qcloud/cos-sdk-v5": "2.*"
    }
}
  1. 使用 Composer 安装,执行以下命令:
php composer.phar install

使用该命令后会在当前目录中创建一个 vendor 文件夹,里面包含 SDK 的依赖库和一个 autoload.php 脚本,方便在项目中调用。

  1. 通过 autoload.php 脚本调用 cos-php-sdk-v5:
require '/path/to/vendor/autoload.php';

现在您的项目已经可以使用 COS 的 V5 版本 SDK 了。

Phar 方式

Phar 方式安装 SDK 的步骤如下:

  1. GitHub 发布页面 下载相应的 phar 文件;

对于 PHP 版本>= 5.6<7.2.5的用户请下载cos-sdk-v5-6.phar以使用 Guzzle6 版本。
对于 PHP 版本>=7.2.5的用户请下载cos-sdk-v5-7.phar以使用 Guzzle7 版本。

  1. 在代码中引入 phar 文件:
require '/path/to/cos-sdk-v5.phar';

源码方式

源码方式安装 SDK 的步骤如下:

  1. GitHub 发布页面 下载相应的 cos-sdk-v5.tar.gz 文件;

对于 PHP 版本>= 5.6<7.2.5的用户请下载cos-sdk-v5-6.tar.gz以使用 Guzzle6 版本。
对于 PHP 版本>=7.2.5的用户请下载cos-sdk-v5-7.tar.gz以使用 Guzzle7 版本。

  1. 解压后通过 autoload.php 脚本加载 SDK:
require '/path/to/cos-sdk-v5/vendor/autoload.php';

快速入门

可参照 Demo 程序,详见 sample 目录

接口文档

PHP SDK 接口文档,详见 https://cloud.tencent.com/document/product/436/12267

配置文件

$cosClient = new Qcloud\Cos\Client(array(
    'region' => '<Region>',
    'credentials' => array(
        'secretId' => '<SecretId>',
        'secretKey' => '<SecretKey>'
    )
));

若您使用 临时密钥 初始化,请用下面方式创建实例。

$cosClient = new Qcloud\Cos\Client(array(
    'region' => '<Region>',
    'credentials' => array(
        'secretId' => '<SecretId>',
        'secretKey' => '<SecretKey>',
        'token' => '<XCosSecurityToken>'
    )
));

上传文件

  • 使用 putObject 接口上传文件(最大 5G)
  • 使用 Upload 接口分块上传文件
# 上传文件
## putObject(上传接口,最大支持上传5G文件)
### 上传内存中的字符串
//bucket 的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
try {
    $result = $cosClient->putObject(array(
        'Bucket' => $bucket,
        'Key' => $key,
        'Body' => 'Hello World!'));
    print_r($result);
} catch (\Exception $e) {
    echo "$e\n";
}

### 上传文件流
try {
    $result = $cosClient->putObject(array(
        'Bucket' => $bucket,
        'Key' => $key,
        'Body' => fopen($local_path, 'rb')));
    print_r($result);
} catch (\Exception $e) {
    echo "$e\n";
}

### 设置header和meta
try {
    $result = $cosClient->putObject(array(
        'Bucket' => $bucket,
        'Key' => $key,
        'Body' => fopen($local_path, 'rb'),
        'ACL' => 'string',
        'CacheControl' => 'string',
        'ContentDisposition' => 'string',
        'ContentEncoding' => 'string',
        'ContentLanguage' => 'string',
        'ContentLength' => integer,
        'ContentType' => 'string',
        'Expires' => 'mixed type: string (date format)|int (unix timestamp)|\DateTime',
        'Metadata' => array(
            'string' => 'string',
        ),
        'StorageClass' => 'string'));
    print_r($result);
} catch (\Exception $e) {
    echo "$e\n";
}

## Upload(高级上传接口,默认使用分块上传最大支持50T)
### 上传内存中的字符串
try {
    $result = $cosClient->Upload(
        $bucket = $bucket,
        $key = $key,
        $body = 'Hello World!');
    print_r($result);
} catch (\Exception $e) {
    echo "$e\n";
}

### 上传文件流
try {
    $result = $cosClient->Upload(
        $bucket = $bucket,
        $key = $key,
        $body = fopen($local_path, 'rb'));
    print_r($result);
} catch (\Exception $e) {
    echo "$e\n";
}

### 设置header和meta
try {
    $result = $cosClient->Upload(
        $bucket= $bucket,
        $key = $key,
        $body = fopen($local_path, 'rb'),
        $options = array(
            'ACL' => 'string',
            'CacheControl' => 'string',
            'ContentDisposition' => 'string',
            'ContentEncoding' => 'string',
            'ContentLanguage' => 'string',
            'ContentLength' => integer,
            'ContentType' => 'string',
            'Expires' => 'mixed type: string (date format)|int (unix timestamp)|\DateTime',
            'Metadata' => array(
                'string' => 'string',
            ),
            'StorageClass' => 'string'));
    print_r($result);
} catch (\Exception $e) {
    echo "$e\n";
}

下载文件

  • 使用 getObject 接口下载文件
  • 使用 getObjectUrl 接口获取文件下载 URL
# 下载文件
## getObject(下载文件)
### 下载到内存
//bucket 的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
try {
    $result = $cosClient->getObject(array(
        'Bucket' => $bucket,
        'Key' => $key));
    echo($result['Body']);
} catch (\Exception $e) {
    echo "$e\n";
}

### 下载到本地
try {
    $result = $cosClient->getObject(array(
        'Bucket' => $bucket,
        'Key' => $key,
        'SaveAs' => $local_path));
} catch (\Exception $e) {
    echo "$e\n";
}

### 指定下载范围
/*
 * Range 字段格式为 'bytes=a-b'
 */
try {
    $result = $cosClient->getObject(array(
        'Bucket' => $bucket,
        'Key' => $key,
        'Range' => 'bytes=0-10',
        'SaveAs' => $local_path));
} catch (\Exception $e) {
    echo "$e\n";
}

### 设置返回header
try {
    $result = $cosClient->getObject(array(
        'Bucket' => $bucket,
        'Key' => $key,
        'ResponseCacheControl' => 'string',
        'ResponseContentDisposition' => 'string',
        'ResponseContentEncoding' => 'string',
        'ResponseContentLanguage' => 'string',
        'ResponseContentType' => 'string',
        'ResponseExpires' => 'mixed type: string (date format)|int (unix timestamp)|\DateTime',
        'SaveAs' => $local_path));
} catch (\Exception $e) {
    echo "$e\n";
}

## getObjectUrl(获取文件Url)
try {
    $signedUrl = $cosClient->getObjectUrl($bucket, $key, '+10 minutes');
    echo $signedUrl;
} catch (\Exception $e) {
    echo "$e\n";
}

cos-php-sdk-v5's People

Contributors

freyo avatar keacefull avatar konakonall avatar krwu avatar lewzylu avatar ming2692 avatar nic12347 avatar overtrue avatar sinkcup avatar sy-records avatar tabll avatar tianyiw2013 avatar tinywan avatar tuuna avatar victorwjwu avatar wi1dcard avatar wormcy avatar yaozongyou avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cos-php-sdk-v5's Issues

your policy or acl has reached the limit

Hi Team,

I am using this plugin from last 1 month. Everything was fine ( uploading images ). But from yesterday onwards I am getting this issue " your policy or acl has reached the limit " in Qcloud\Cos\Exception\ServiceResponseException.

Due to this I am unable upload any images to cloud..

Can you please help me out

Thanks in advance!!!!

V1.1.2 版本中居然还有print_r()

具体如下:

文件:qcloud\cos-sdk-v5\src\Qcloud\Cos\Client.php

public function upload($bucket, $key, $body, $options = array()) {
$body = EntityBody::factory($body);
$options = Collection::fromConfig(array_change_key_case($options), array(
'min_part_size' => MultipartUpload::MIN_PART_SIZE,
'params' => $options));
print_r($options);
if ($body->getSize() < $options['min_part_size']) {
// Perform a simple PutObject operation
return $this->putObject(array(
'Bucket' => $bucket,
'Key' => $key,
'Body' => $body,
) + $options['params']);
}

第103 行 居然还有一个print_r ....

PHP对象存储cos-sdk-v5依赖的guzzle升级造成不兼容

PHP版本 7.1
上传COS文件代码

            $result = $this->cosClient->Upload(
                $bucket = $bucketName,
                $key = $KeyForUpload,
                $body = $file
            );

将qcloud/cos-sdk-v5版本从1.3.2升级成为1.3.4,由于该SDK依赖的guzzle包升级成为guzzlehttp导致返回的 $result变量的值发生了改变,$result["Location"] 取值不存在,无法获取COS文件的URL地址,希望作者在升级版本时标注一下版本改动情况

== Debug output of model == debug信息怎么控制不显示?

==================== Debug output of model ===================== Model data ----------- This data can be retrieved from the model object using the get() method of the model (e.g. $model->get($key)) or accessing the model like an associative array (e.g. $model['key']). [Expiration] => [ETag] => "67b55d5c51dfa185bc8360701975e36f" [ServerSideEncryption] => [VersionId] => [SSECustomerAlgorithm] => [SSECustomerKeyMD5] => [SSEKMSKeyId] => [RequestCharged] => [RequestId] => NWE0ZTM3ODdfMWJiMjk0MGFfYjMxYV9jMmNjNg== [ObjectURL] => http://timelang-1253895285.cos.ap-guangzhou.myqcloud.com/cms%2Fuploadfile%2F201801%2F38b2b23111.png

返回的url 没有 cdn 加速域名的链接

    "Expiration": "",
    "ETag": "\"19f6bc7c91552d33161c246c4f67be92\"",
    "ServerSideEncryption": "",
    "VersionId": "",
    "SSECustomerAlgorithm": "",
    "SSECustomerKeyMD5": "",
    "SSEKMSKeyId": "",
    "RequestCharged": "",
    "RequestId": "NWE0ZTM1N2FfYzZhMzNiMGFfNGYzYV9jMmYyMg==",
    "ObjectURL": "http://timelang-1253895285.cos.ap-guangzhou.myqcloud.com/cms%2Fuploadfile%2F201801%2Fd966ce5359.png"
}

我用java的sdk可以取到带cdn 加速域名的文件url
php的怎么改?

当listContents()带有prefix或Delimiter时,会二次urlencode导致签名失败

public function createAuthorization( RequestInterface $request, $expires = '+30 minutes' ) { 。。。 foreach ( explode( '&', $request->getUri()->getQuery() ) as $query ) { if (!empty($query)) { $tmpquery = explode( '=', $query ); $key = strtolower( urlencode( $tmpquery[0] ) ); if (count($tmpquery) >= 2) { $value = urlencode( $tmpquery[1] ); } else { $value = ""; } $urlParamListArray[$key] = $key. '='. $value; } } 。。。 }
$request->getUri()->getQuery()

urlencode( $tmpquery[1] )
会两次urlencode,造成签名失败

请注释掉无用的打印输出

@moria @yaozongyou @yishuiliunian @puterjam @konakonall
调试接口的时候,莫名奇妙的多了下面一行字符,这些是无用的输出,会影响接口的使用,如果会可以去掉,请注释掉

Guzzle\Common\Collection Object ( [data:protected] => Array ( [min_part_size] => 5242880 [params] => Array ( ) ) )

代码位置:qcloud\cos-sdk-v5\src\Qcloud\Cos\Client.php 第103行 print_r($options);

Input is not proper UTF-8, indicate encoding

PHP Warning:  SimpleXMLElement::__construct(): Entity: line 4: parser error : Input is not proper UTF-8, indicate encoding !
Bytes: 0xB4 0xED 0xCE 0xF3 in /data/builds/vote.wj.qq.com/cos/vendor/qcloud/cos-sdk-v5/src/Qcloud/Cos/ExceptionParser.php on line 30

Warning: SimpleXMLElement::__construct(): Entity: line 4: parser error : Input is not proper UTF-8, indicate encoding !
Bytes: 0xB4 0xED 0xCE 0xF3 in /data/builds/vote.wj.qq.com/cos/vendor/qcloud/cos-sdk-v5/src/Qcloud/Cos/ExceptionParser.php on line 30
PHP Warning:  SimpleXMLElement::__construct(): <TITLE>´£ºź̹ȫȳµō򷣨URL£©Ϟ·¨»򈟼/TITLE> in /data/builds/vote.wj.qq.com/cos/vendor/qcloud/cos-sdk-v5/src/Qcloud/Cos/ExceptionParser.php on line 30

release版 cos-php-sdk-v5-1.1.4 测试报错!

下载的是最新release版 release v1.1.4
cos-php-sdk-v5-1.1.4
报错:

Qcloud\Cos\Exception\ServiceResponseException: Cos Error Code: InvalidAccessKeyId, Status Code: 403, Cos Request ID: NWFkZWIwY2VfMjRiMjU4NjRfNmYzZV83N2JkNw==, Cos Error Type: client, Cos Error Message: The Access Key Id you provided does not exist in our records

代码截图:
image

求助!第一次使用相信腾讯的实力!不应该这样!ps:我用的COS是官方提供的免费体验COS API秘钥也配置过配置如图!马上需要使用COS预先测试下!

上传图片但header显示的是application/octet-stream

如图,上传图片,假如是jpg的,content-type应该是image/jpeg,png图片应该是image/png,gif应该是image/gif,而不是全都是application/octet-stream
image

上传代码如下:

$cosClient = new Client([
    'region' => $this->region,
    'credentials' => [
        'secretId' => $this->secretId,
        'secretKey' => $this->secretKey,
    ],
]);

$fp = fopen($uploadFilePath, 'rb');
/** @var Result $retObj */
$retObj = $cosClient->Upload($this->bucket, $key, $fp);
is_resource($fp) && fclose($fp);

install

symfony/event-dispatcher suggests installing symfony/dependency-injection ()
symfony/event-dispatcher suggests installing symfony/http-kernel ()
guzzle/guzzle suggests installing guzzlehttp/guzzle (Guzzle 5 has moved to a new package name. The package you have installed, Guzzle 3, is deprecated.)
Package guzzle/guzzle is abandoned, you should avoid using it. Use guzzlehttp/guzzle instead.

request.options参数配置

Qcloud\Cos\Client::__construct()里面request.options应该把proxy参数默认也带进去,不然这配置代理的话很麻烦。

为何返回回来的data前面有*

array(2) {
  ["*structure"] => NULL
  ["*data"] => array(10) {
    ["Expiration"] => string(0) ""
    ["ETag"] => string(34) ""27685a34a98914d218329a9136cd777d""
    ["ServerSideEncryption"] => string(0) ""
    ["VersionId"] => string(0) ""
    ["SSECustomerAlgorithm"] => string(0) ""
    ["SSECustomerKeyMD5"] => string(0) ""
    ["SSEKMSKeyId"] => string(0) ""
    ["RequestCharged"] => string(0) ""
    ["RequestId"] => string(40) "NWI5OGU2NjRfMmI5ZDA4MDlfMWNlZl82NTIyOWM="
    ["ObjectURL"] => string(117) "http://csfc-test-1256260708.cos.ap-shanghai.myqcloud.com//uploads/20180912/27685a34a98914d218329a9136cd777d.png"
  }
}

为何返回回来的data前面有*

代码写的太随意了

函数命名有的蛇形有的驼峰,甚至有的首字母大写,还跟文档对应不起来,完全取消了使用的想法,这么大的个公司

能不能更新下 guzzle这包呢?

IDE 提示 guzzle/guzzle 过期了,是不是可以更新到新的包guzzlehttp/guzzle

Package guzzle/guzzle is abandoned, you should avoid using it. Use guzzlehttp/guzzle instead.

Bug: 'NoSuchBucket' Exception is thrown when an object doesn't exists.

When you try to retrieve a non-exist object from an exists bucket, It should throw NoSuchKeyException, not NoSuchBucketException.

Test code:

$client = new Client(array(
    'region' => 'gz',
    'credentials' => array(
        'appId' => '{appId}',
        'secretId' => '{secretId}',
        'secretKey' => '{secretKey}'
    )
));

try {
    $result = $client->headObject(array(
        'Bucket' => '{exists bucket}',
        'Key' => '{non-exists key}'
    ));
    print_r($result);
} catch ( NoSuchKeyException $e ) {
    echo 'No such key.';
} catch ( NoSuchBucketException $e) {
    echo 'No such bucket.';
}

The output will be "No such bucket."

$this->signature 值是否未进行初始化?

版本:v1.3.4
文件:/src/Qcloud/Cos/UploadBodyMiddleware.php
运行报错:Call to a member function signRequest() on null
看了下代码,好像是这个地方:
public function __invoke(RequestInterface $request, array $options) {
$fn = $this->nextHandler;
return $fn($this->signature->signRequest($request), $options);
}
是不是$this->signature没有进行初始化,v1.3.3是正常得,v1.3.4会报错。

获取文件列表

你已经是个成熟的sdk了,获取文件列表的时候增加几个参数来排序吧,比如按时间,文件大小等等,现在是名字吧

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.