aws s3 php api

AWS SDK для PHP

Начните работу с AWS в кратчайшие сроки, используя AWS SDK для PHP. SDK представляет собой современную библиотеку PHP с открытым исходным кодом, которая упрощает интеграцию приложения на PHP с такими сервисами AWS, как Amazon S3, Amazon Glacier и Amazon DynamoDB.

Установить

Новое в версии 3 AWS SDK для PHP

Версия 3 AWS SDK для PHP стала общедоступной. Она включает в себя ряд усовершенствований и новых возможностей, сохраняя при этом практически идентичные прежним шаблоны API для легкого перехода с версии 2.

Другие возможности

Без труда формируйте и разбивайте документы JSON и массивы PHP для хранения в Amazon DynamoDB.

Сохраняйте состояние сеанса приложения в сервисе DynamoDB, чтобы устранить узкие места в масштабировании состояния сеанса.

Используйте встроенные функции PHP, такие как «fopen», «copy» и «file_get_contents», для работы с объектами, находящимися на хранении в Amazon S3.

Автоматизирует опросы изменений состояния ресурсов, например, для ожидания перехода недавно запущенного инстанса Amazon EC2 в рабочее состояние.

Предварительный просмотр ресурсных API AWS для AWS SDK для PHP

Ресурсные API AWS обеспечивают объектно-ориентированное представление низкоуровневого или RPC-интерфейса в AWS SDK для PHP, что упрощает процесс написания кода и делает его более интуитивным. Ресурсный объект представляет собой ссылку на ресурс AWS (например, инстанс Amazon EC2 или объект Amazon S3), которая отображает атрибуты ресурса и действия в качестве свойств и методов ресурсного объекта. Сведения о базовых запросах HTTP API становятся доступными, а работа с ресурсами AWS – такой же удобной, как с локальными объектами PHP. Ниже приведен образец кода, который показывает принципы работы. Список поддерживаемых сервисов включает Amazon EC2, Amazon S3, Amazon SNS, Amazon SQS, AWS IAM, Amazon Glacier и AWS CloudFormation. В будущем планируется добавить и другие сервисы.

Установить

Дополнительные ресурсы

Получите рекомендации по переходу на новую версию AWS SDK для PHP, ознакомившись с руководством по миграции »

Просматривайте исходный код в репозитории GitHub »

Узнайте о возможностях новой версии SDK в списке изменений »

Общайтесь с другими разработчиками на форуме сообщества PHP-разработчиков »

Получите дополнительные сведения об использовании PHP в AWS в центре для PHP-разработчиков

Ищете старые версии AWS SDK для PHP?

AWS SDK для PHP – версия 2 доступна в разделе «v2» GitHub

Источник

Using the AWS SDK for PHP and Running PHP Examples

The AWS SDK for PHP provides access to the API for Amazon S3 bucket and object operations. The SDK gives you the option of using the service’s low-level API or using higher-level abstractions.

The setup for using the AWS SDK for PHP depends on your environment and how you want to run your application. To set up your environment to run the examples in this documentation, see the AWS SDK for PHP Getting Started Guide.

Topics

AWS SDK for PHP Levels

The AWS SDK for PHP gives you the option of using a high-level or low-level API.

Low-Level API

The low-level APIs correspond to the underlying Amazon S3 REST operations, including the create, update, and delete operations on buckets and objects. The low-level APIs provide greater control over these operations. For example, you can batch your requests and run them in parallel. Or, when using the multipart upload API, you can manage the object parts individually. Note that these low-level API calls return a result that includes all of the Amazon S3 response details. For more information about the multipart upload API, see Uploading and copying objects using multipart upload.

High-Level Abstractions

As another example, when enumerating objects in a bucket, you can use the iterators feature of the AWS SDK for PHP to return all of the object keys, regardless of how many objects you have stored in the bucket. If you use the low-level API, the response returns a maximum of 1,000 keys. If a bucket contains more than 1,000 objects, the result is truncated and you have to manage the response and check for truncation.

Running PHP Examples

To set up and use the Amazon S3 samples for version 3 of the AWS SDK for PHP, see Installation in the AWS SDK for PHP Developer Guide.

Источник

Installing the AWS SDK for PHP Version 3

You can install the AWS SDK for PHP Version 3:

As a dependency via Composer

As a prepackaged phar of the SDK

As a ZIP file of the SDK

Before you install AWS SDK for PHP Version 3 ensure your environment is using PHP version 5.5 or later. Learn more about environment requirements and recommendations.

Install AWS SDK for PHP as a dependency via Composer

Install Composer

Add AWS SDK for PHP as a dependency via Composer

Otherwise type this Composer command to install the latest version of the AWS SDK for PHP as a dependency.

Add autoloader to your php scripts

To utilize the AWS SDK for PHP in your scripts, include the autoloader in your scripts, as follows.

Installing by Using the Packaged Phar

Each release of the AWS SDK for PHP includes a prepackaged phar (PHP archive) that contains all the classes and dependencies you need to run the SDK. Additionally, the phar automatically registers a class autoloader for the AWS SDK for PHP and all its dependencies.

You can download the packaged phar and include it in your scripts.

Using PHP with the Suhosin patch is not recommended, but is common on Ubuntu and Debian distributions. In this case, you might need to enable the use of phars in the suhosin.ini. If you don’t do this, including a phar file in your code will cause a silent failure. To modify suhosin.ini, add the following line.

Installing by Using the ZIP file

The AWS SDK for PHP includes a ZIP file containing all the classes and dependencies you need to run the SDK. Additionally, the ZIP file includes a class autoloader for the AWS SDK for PHP and its dependencies.

Источник

Basic Usage Patterns of the AWS SDK for PHP Version 3

This topic focuses on basic usage patterns of the AWS SDK for PHP.

Prerequisites

Including the SDK in Your Code

No matter which technique you used to install the SDK, you can include the SDK in your code with just a single require statement. See the following table for the PHP code that best fits your installation technique. Replace any instances of /path/to/ with the actual path on your system.

In this topic, we show examples that assume the Composer installation method. If you’re using a different installation method, you can refer back to this section to find the correct require code to use.

Usage Summary

To use the SDK to interact with an AWS service, instantiate a Client object. Client objects have methods that correspond one to one with operations in the service’s API. To execute a particular operation, you call its corresponding method. This method either returns an array-like Result object on success, or throws an Exception on failure.

Creating a Client

You can create a client by passing an associative array of options to a client’s constructor.

Notice that we did not explicitly provide credentials to the client. That’s because the SDK should detect the credentials from environment variables (via AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY ), an AWS credentials INI file in your HOME directory, AWS Identity and Access Management (IAM) instance profile credentials, or credential providers.

All of the general client configuration options are described in detail in the configuration guide. The array of options provided to a client can vary based on which client you’re creating. These custom client configuration options are described in the API documentation for each client.

Using the Sdk Class

The Aws\Sdk class acts as a client factory and is used to manage shared configuration options across multiple clients. The same options that can be provided to a specific client constructor can also be supplied to the Aws\Sdk class. These options are then applied to each client constructor.

Options that are shared across all clients are placed in root-level key-value pairs. Service-specific configuration data can be provided in a key that is the same as the namespace of a service (e.g., “S3”, “DynamoDb”, etc.).

Service-specific configuration values are a union of the service-specific values and the root-level values (i.e., service-specific values are shallow-merged onto root-level values).

We highly recommended that you use the Sdk class to create clients if you’re using multiple client instances in your application. The Sdk class automatically uses the same HTTP client for each SDK client, allowing SDK clients for different services to perform nonblocking HTTP requests. If the SDK clients don’t use the same HTTP client, then HTTP requests sent by the SDK client might block promise orchestration between services.

Executing Service Operations

You can execute a service operation by calling the method of the same name on a client object. For example, to perform the Amazon S3 PutObject operation, you must call the Aws\S3\S3Client::putObject() method.

Operations available to a client and the structure of the input and output are defined at runtime based on a service description file. When creating a client, you must provide a version (e.g., “2006-03-01” or “latest”). The SDK finds the corresponding configuration file based on the provided version.

Operation methods like putObject() all accept a single argument, an associative array that represents the parameters of the operation. The structure of this array (and the structure of the result object) is defined for each operation in the SDK’s API Documentation (e.g., see the API docs for putObject operation).

HTTP Handler Options

You can also fine-tune how the underlying HTTP handler executes the request by using the special @http parameter. The options you can include in the @http parameter are the same as the ones you can set when you instantiate the client with the “http” client option.

Asynchronous Requests

You can force a promise to complete synchronously by using the wait method of the promise. Forcing the promise to complete also “unwraps” the state of the promise by default, meaning it will either return the result of the promise or throw the exception that was encountered. When calling wait() on a promise, the process blocks until the HTTP request is completed and the result is populated or an exception is thrown.

When using the SDK with an event loop library, don’t block on results. Instead, use the then() method of a result to access a promise that is resolved or rejected when the operation completes.

Working with Result Objects

Executing a successful operation returns an Aws\Result object. Instead of returning the raw XML or JSON data of a service, the SDK coerces the response data into an associative array structure. It normalizes some aspects of the data based on its knowledge of the specific service and the underlying response structure.

You can access data from the AWSResult object like an associative PHP array.

The contents of the result object depend on the operation that was executed and the version of a service. The result structure of each API operation is documented in the API docs for each operation.

Handling Errors

Synchronous Error Handling

If an error occurs while performing an operation, an exception is thrown. For this reason, if you need to handle errors in your code, use try / catch blocks around your operations. The SDK throws service-specific exceptions when an error occurs.

Asynchronous Error Handling

Exceptions are not thrown when sending asynchronous requests. Instead, you must use the then() or otherwise() method of the returned promise to receive the result or error.

You can “unwrap” the promise and cause the exception to be thrown instead.

Источник

Class S3Client

Client used to interact with Amazon Simple Storage Service (Amazon S3).

Supported API Versions

Methods Summary

Get an array of client constructor arguments used by the client.

The client constructor accepts the following options:

Determine if a string is a valid name for a DNS compatible Amazon S3 bucket.

Create a pre-signed URL for the given S3 command object.

Returns the URL to an object identified by its bucket and key.

Raw URL encode a key and allow for ‘/’ characters

Methods inherited from Aws\AwsClient

Methods inherited from Aws\AwsClientInterface

Methods inherited from Aws\S3\S3ClientInterface

Methods used from Aws\S3\S3ClientTrait

Methods used from Aws\AwsClientTrait

Methods Details

static array getArguments ( )

Get an array of client constructor arguments used by the client.

Returns

Overrides

The client constructor accepts the following options:

In addition to the options available to Aws\AwsClient::__construct, S3Client accepts the following options:

Parameters

Exceptions

if any required options are missing or the service is not supported.

Overrides

Determine if a string is a valid name for a DNS compatible Amazon S3 bucket.

Parameters

Returns

Create a pre-signed URL for the given S3 command object.

Parameters

Command to create a pre-signed URL for.

The time at which the URL should expire. This can be a Unix timestamp, a PHP DateTime object, or a string that can be evaluated by strtotime().

Returns

Implementation of

Returns the URL to an object identified by its bucket and key.

The URL returned by this method is not signed nor does it ensure that the bucket and key given to the method exist. If you need a signed URL, then use the \Aws\S3\S3Client::createPresignedRequest method and get the URI of the signed request.

Parameters

string$bucketThe name of the bucket where the object is located
string$keyThe key of the object

Returns

Implementation of

Raw URL encode a key and allow for ‘/’ characters

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *