Aliyun OSS SDK for PHP

Overview

Alibaba Cloud OSS SDK for PHP

Latest Stable Version Build Status Coverage Status

README of Chinese

Overview

Alibaba Cloud Object Storage Service (OSS) is a cloud storage service provided by Alibaba Cloud, featuring a massive capacity, security, a low cost, and high reliability. You can upload and download data on any application anytime and anywhere by calling APIs, and perform simple management of data through the web console. The OSS can store any type of files and therefore applies to various websites, development enterprises and developers.

Run environment

  • PHP 5.3+.
  • cURL extension.

Tips:

  • In Ubuntu, you can use the apt-get package manager to install the PHP cURL extension: sudo apt-get install php5-curl.

Install OSS PHP SDK

  • If you use the composer to manage project dependencies, run the following command in your project's root directory:

      composer require aliyuncs/oss-sdk-php
    

    You can also declare the dependency on Alibaba Cloud OSS SDK for PHP in the composer.json file.

      "require": {
          "aliyuncs/oss-sdk-php": "~2.0"
      }
    

    Then run composer install to install the dependency. After the Composer Dependency Manager is installed, import the dependency in your PHP code:

      require_once __DIR__ . '/vendor/autoload.php';
    
  • You can also directly download the packaged PHAR File, and introduce the file to your code:

      require_once '/path/to/oss-sdk-php.phar';
    
  • Download the SDK source code, and introduce the autoload.php file under the SDK directory to your code:

      require_once '/path/to/oss-sdk/autoload.php';
    

Quick use

Common classes

Class Explanation
OSS\OssClient OSS client class. An OssClient instance can be used to call the interface.
OSS\Core\OssException OSS Exception class . You only need to pay attention to this exception when you use the OssClient.

Initialize an OssClient

The SDK's operations for the OSS are performed through the OssClient class. The code below creates an OssClient object:

<?php
$accessKeyId = "<AccessKeyID that you obtain from OSS>";
$accessKeySecret = "<AccessKeySecret that you obtain from OSS>";
$endpoint = "<Domain that you select to access an OSS data center, such as "oss-cn-hangzhou.aliyuncs.com>";
try {
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
} catch (OssException $e) {
    print $e->getMessage();
}

Operations on objects

Objects are the most basic data units on the OSS. You can simply consider objects as files. The following code uploads an object:

<?php
$bucket= "<Name of the bucket in use. Pay attention to naming conventions>";
$object = "<Name of the object in use. Pay attention to naming conventions>";
$content = "Hello, OSS!"; // Content of the uploaded file
try {
    $ossClient->putObject($bucket, $object, $content);
} catch (OssException $e) {
    print $e->getMessage();
}

Operations on buckets

Buckets are the space that you use to manage the stored objects. It is an object management unit for users. Each object must belong to a bucket. You can create a bucket with the following code:

<?php
$bucket= "<Name of the bucket in use. Pay attention to naming conventions>";
try {
    $ossClient->createBucket($bucket);
} catch (OssException $e) {
    print $e->getMessage();
}

Handle returned results

The OssClient provides the following two types of returned data from interfaces:

  • Put and Delete interfaces: The PUT and DELETE operations are deemed successful if null is returned by the interfaces without OSSException.

  • Get and List interfaces: The GET and LIST operations are deemed successful if the desired data is returned by the interfaces without OSSException. For example,

    <?php
    $bucketListInfo = $ossClient->listBuckets();
    $bucketList = $bucketListInfo->getBucketList();
    foreach($bucketList as $bucket) {
        print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreateDate() . "\n");
    }

In the above code, $bucketListInfo falls into the 'OSS\Model\BucketListInfo' data type.

Run a sample project

  • Modify samples/Config.php to complete the configuration information.
  • Run cd samples/ && php RunAll.php.

Run a unit test

  • Run composer install to download the dependent libraries.

  • Set the environment variable.

      export OSS_ACCESS_KEY_ID=access-key-id
      export OSS_ACCESS_KEY_SECRET=access-key-secret
      export OSS_ENDPOINT=endpoint
      export OSS_BUCKET=bucket-name
    
  • Run php vendor/bin/phpunit

License

  • MIT

Contact us

Comments
  • 支持Swoole的cURL handle

    支持Swoole的cURL handle

    支持Swoole的cURL handle,运行测试环境:

    $php --version PHP 7.4.14 (cli) (built: Mar 23 2021 11:21:02) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0, Copyright (c) Zend Technologies

    $php --ri swoole

    swoole

    Swoole => enabled Author => Swoole Team [email protected] Version => 4.6.2 Built => Mar 23 2021 16:33:39 coroutine => enabled with boost asm context kqueue => enabled rwlock => enabled openssl => OpenSSL 1.1.1j 16 Feb 2021 dtls => enabled http2 => enabled pcre => enabled zlib => 1.2.11 async_redis => enabled

    Directive => Local Value => Master Value swoole.enable_coroutine => On => On swoole.enable_library => On => On swoole.enable_preemptive_scheduler => Off => Off swoole.display_errors => On => On swoole.use_shortname => Off => Off swoole.unixsock_buffer_size => 262144 => 262144

    opened by coleflowers 8
  • 上传完成以后,PutSetDeleteResult 解析上传结果的逻辑没有实现

    上传完成以后,PutSetDeleteResult 解析上传结果的逻辑没有实现

    https://github.com/aliyun/aliyun-oss-php-sdk/blob/v2.1.0/src/OSS/Result/PutSetDeleteResult.php#L17

    响应上可以获取上传后的result的,包括返回的文件的md5的etag头 ,文件网址等。

    image

    其他SDK都有实现了的 官方说明

    代码出处1

    代码出处2

    opened by ihipop 6
  • 使用签名URL临时授权上传文件SignatureDoesNotMatch

    使用签名URL临时授权上传文件SignatureDoesNotMatch

    获取临时签名

    $ossClient = new OssClient('access_key_id', 'access_key_secret', 'endpoint');
    echo $ossClient->signUrl('bucket', '20201222_082037_1.jpg', 3600, OssClient::OSS_HTTP_PUT);
    
    // https://bpit-test.oss-cn-beijing.aliyuncs.com/20201222_082037_1.jpg?OSSAccessKeyId=LTAI4G76TwXmUuxxxxxxxx&Expires=1608690732&Signature=s%2BEMGbWNo4Z9PhV7ba661oq2Tzo%3D
    

    拿到签名后,使用Postman,PUT,上传文件,返回信息如下:

    如果不选择任何文件,直接发起PUT请求,则会请求成功,阿里云对应bucket也会生成一个大小为0kb的文件

    <?xml version="1.0" encoding="UTF-8"?>
    <Error>
        <Code>SignatureDoesNotMatch</Code>
        <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message>
        <RequestId>5FE2B07E50ED1C3034C9258B</RequestId>
        <HostId>bpit-test.oss-cn-beijing.aliyuncs.com</HostId>
        <OSSAccessKeyId>LTAI4G76TwXmxxxxxxxxxxxxx</OSSAccessKeyId>
        <SignatureProvided>JF8uyXl9rGl9/doXf/PPFJt2fC0=</SignatureProvided>
        <StringToSign>PUT
    
    image/jpeg
    1608695222
    /bpit-test/20201222_082037_1.jpg</StringToSign>
        <StringToSignBytes>50 55 54 0A 0A 69 6D 61 67 65 2F 6A 70 65 67 0A 31 36 30 38 36 39 35 32 32 32 0A 2F 62 70 69 74 2D 74 65 73 74 2F 32 30 32 30 31 32 32 32 5F 30 38 32 30 33 37 5F 31 2E 6A 70 67 </StringToSignBytes>
    </Error>
    
    opened by sxin0 4
  • 关于signUrl方法加密时候的bug

    关于signUrl方法加密时候的bug

    在 ossClient 2154行有一行代码:

     if (
                    strtolower($header_key) === 'content-md5' ||
                    strtolower($header_key) === 'content-type' ||
                    strtolower($header_key) === 'date' ||
                    (isset($options['self::OSS_PREAUTH']) && (integer)$options['self::OSS_PREAUTH'] > 0)
                ) {
                    $string_to_sign .= $header_value . "\n";
                } elseif (substr(strtolower($header_key), 0, 6) === self::OSS_DEFAULT_PREFIX) {
                    $string_to_sign .= strtolower($header_key) . ':' . $header_value . "\n";
                }
    

    很明显是 键名写错了,但是却并不会影响signUrl的方法使用 但是如果改为正常代码

     if (
                    strtolower($header_key) === 'content-md5' ||
                    strtolower($header_key) === 'content-type' ||
                    strtolower($header_key) === 'date' ||
                    (isset($options[self::OSS_PREAUTH]) && (integer)$options[self::OSS_PREAUTH] > 0)
                ) {
                    $string_to_sign .= $header_value . "\n";
                } elseif (substr(strtolower($header_key), 0, 6) === self::OSS_DEFAULT_PREFIX) {
                    $string_to_sign .= strtolower($header_key) . ':' . $header_value . "\n";
                }
    

    验签将会出错. 可能是前面少了个! ?

    opened by tioncico 4
  • Translating into English

    Translating into English

    Hi

    This sdk document is Chinese. But we Japanese also use this library. Will you tranlate it into English? If I request PR of translating into English, do you merge?

    opened by mosuke5 4
  • 自定义域名后开启 CDN 加速 bug

    自定义域名后开启 CDN 加速 bug

    问题

    开启自定义域名之后此时上传没有问题,然后再开 cdn 加速上传就有问题,直接报错

    endpoint: http://os.xxxx.com bucket: xxx isCname: true

    client->putObject($this->bucket, $path, $contents, $options);
    

    报错信息

    {
        "status": "403",
        "request-id": "5E7F892260097C32372045DE",
        "code": "",
        "message": "",
        "body": ""
    }
    
    opened by iiDestiny 3
  • File size 0

    File size 0

    When I upload an image sometimes it has a size_upload response of 0, and when I check in the bucket image is not rendering (probably because file size = 0). But not all images just for some images.

    image

    opened by rwaddin 0
  • 简单上传:上传成功后,地址可以访问但都是空白

    简单上传:上传成功后,地址可以访问但都是空白

    使用sdk的简单上传

    ···php composer show aliyuncs/oss-sdk-php

    name : aliyuncs/oss-sdk-php descrip. : Aliyun OSS SDK for PHP keywords : versions : * v2.4.3 php >=5.3

    requires (dev) phpunit/phpunit * satooshi/php-coveralls * ··· 第一行fopen 保证文件能够获取到是个资源

    Ossclient.phpuploadFile打印$option 得到array结果,可以看到uploadFile参数是临时缓存目录资源,object为txt后缀的oss目录

    image

    同时在func generateHeaders 如果不拼接content-type 则会报MissingContentLength 错误

    所以在其中添加

    if (isset($options[self::OSS_CONTENT_LENGTH])) {
              $headers[self::OSS_CONTENT_LENGTH] = $options[self::OSS_CONTENT_LENGTH];
          }
    

    此后可以上传成功,但是上传结果为空白,不仅仅是png,xlsx,doc等都为空白文件(上传之前确定文件可以打开,且有数据)

    opened by ylnwqm 0
Releases(v2.6.0)
Owner
Alibaba Cloud
More Than Just Cloud
Alibaba Cloud
Zoho CRM API SDK is a wrapper to Zoho CRM APIs. By using this sdk, user can build the application with ease

Archival Notice: This SDK is archived. You can continue to use it, but no new features or support requests will be accepted. For the new version, refe

null 81 Nov 4, 2022
The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructure and leverage the power of 1Password Secrets Automation

1Password Connect PHP SDK The 1Password Connect PHP SDK provides your PHP applications access to the 1Password Connect API hosted on your infrastructu

Michelangelo van Dam 12 Dec 26, 2022
Facebook SDK for PHP (v6) - allows you to access the Facebook Platform from your PHP app

Facebook SDK for PHP (v6) This repository contains the open source PHP SDK that allows you to access the Facebook Platform from your PHP app. Installa

null 0 Aug 10, 2022
Unofficial Firebase Admin SDK for PHP

Firebase Admin PHP SDK Table of Contents Overview Installation Documentation Support License Overview Firebase provides the tools and infrastructure y

kreait 1.9k Jan 3, 2023
Notion PHP SDK

Notion PHP SDK This is an unofficial PHP SDK for the new public Notion API. It's work in progress as we didn't get the change to be included to the pr

Codecycler 43 Nov 29, 2022
爱发电非官方简易 PHP SDK

afdian-php-sdk 爱发电非官方简易 PHP SDK by Akkariin 这是一个简单的 SDK,可以用于查询爱发电的订单和赞助者信息 Installation 将项目 clone 到本地即可 git clone https://github.com/ZeroDream-CN/afdi

ZeroDream-CN 17 Nov 7, 2022
AWS Cognito package using the AWS SDK for PHP/Laravel

Laravel Package to manage Web and API authentication with AWS Cognito AWS Cognito package using the AWS SDK for PHP This package provides a simple way

EllaiSys 74 Nov 15, 2022
PHP SDK to interact with the Casper Network nodes via RPC

casper-php-sdk PHP SDK to interact with Casper Network nodes via RPC Install composer require make-software/casper-php-sdk Examples RPC Client: $node

MAKE Technology LLC 7 May 8, 2022
A Laravel 5+ (and 4) service provider for the AWS SDK for PHP

AWS Service Provider for Laravel 5/6/7/8 This is a simple Laravel service provider for making it easy to include the official AWS SDK for PHP in your

Amazon Web Services 1.5k Dec 28, 2022
A complete Notion SDK for PHP developers.

notion-sdk-php A complete Notion SDK for PHP developers. Installation composer require mariosimao/notion-php Getting started A Notion token will be n

Mario Simão 77 Nov 29, 2022
SDK of the LINE Login API for PHP

LINE Login for PHP SDK of the LINE Login API for PHP Documentation See the official API documentation for more information. Installation Use the packa

null 4 Sep 15, 2022
PHP SDK - Flexie CRM fiskalizimi solution

PHP SDK - Flexie CRM fiskalizimi solution Fiskalizimi PHP SDK allows you to talk and generate your e-invoices programmatically from your own solution

Flexie CRM 3 Dec 30, 2021
PHP Digital Green Certificate SDK

Digital Green Certificate SDK PHP Indice Contesto Installazione Uso Licenza Dettaglio licenza Contesto Attenzione, questo repository è derivato dalle

null 13 Jun 20, 2022
Esse SDK em PHP foi desenvolvido no intuito de tornar mais prático a integração com nossa API.

Sobre Beedoo SDK Acessar documentação completa da Beedoo API. A API é organizada seguindo a arquitetura REST, boas práticas, convenções e padrões como

Beedoo Edtech 5 Dec 2, 2021
A PHP SDK for accessing the OpenAI GPT-3 API

OpenAI GPT-3 Api Client in PHP Installation You can install the package via composer: composer require orhanerday/open-ai Usage use Orhanerday\OpenAi\

Orhan erday 462 Jan 2, 2023
The Facebook SDK for PHP provides a native interface to the Graph API and Facebook Login

Facebook SDK for PHP (v5) This repository contains the open source PHP SDK that allows you to access the Facebook Platform from your PHP app. Installa

Meta Archive 3.1k Dec 30, 2022
PHP SDK for the Sellix Developers API (developers.sellix.io)

PHP SDK for the Sellix Developers API (developers.sellix.io). Quickly get started and create products, payments and more using PHP.

Sellix 7 Nov 23, 2022
Alibaba Cloud SDK for PHP

English | 简体中文 Alibaba Cloud SDK for PHP Alibaba Cloud SDK for PHP is a development kit that supports quick access to products, dependency on Alibaba

Alibaba Cloud 493 Dec 16, 2022
Qiniu Resource (Cloud) Storage SDK for PHP

Qiniu Cloud SDK for PHP 安装 推荐使用 composer 进行安装。可以使用 composer.json 声明依赖,或者运行下面的命令。SDK 包已经放到这里 qiniu/php-sdk 。 $ composer require qiniu/php-sdk 直接下载安装,SD

Qiniu Cloud 804 Dec 19, 2022