如何直接在 PHP (AWS SDK for PHP) 中將檔案從 S3 存盤桶復制到 S3 存盤桶?我正在尋找 Ruby 的示例,即:https : //stackoverflow.com/a/10418427/2899889 但我找不到 php 的單個示例。此外,我在適用于 PHP 的 AWS 開發工具包中找不到方法 copy_to() 或 copy_from() - Ruby 示例中使用的命令?
uj5u.com熱心網友回復:
有關代碼示例,請參閱AWS Github。
當您想學習如何使用 AWS 開發工具包以受支持的編程語言執行任務時,這是您應該首先考慮的地方。
以下是 Amazon S3 的 PHP 代碼示例:
https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/s3
這是從aws-doc-sdk-examples/s3-copying-objects.php復制物件的示例,位于 main · awsdocs/aws-doc-sdk-examples · GitHub:
<?php
/**
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* This file is licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* ABOUT THIS PHP SAMPLE: This sample is part of the SDK for PHP Developer Guide topic at
* https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/s3-examples-creating-buckets.html
*
*/
require 'vendor/autoload.php';
use Aws\S3\S3Client;
$sourceBucket = '*** Your Source Bucket Name ***';
$sourceKeyname = '*** Your Source Object Key ***';
$targetBucket = '*** Your Target Bucket Name ***';
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-east-1'
]);
// Copy an object.
$s3->copyObject([
'Bucket' => $targetBucket,
'Key' => "{$sourceKeyname}-copy",
'CopySource' => "{$sourceBucket}/{$sourceKeyname}",
]);
// Perform a batch of CopyObject operations.
$batch = array();
for ($i = 1; $i <= 3; $i ) {
$batch[] = $s3->getCommand('CopyObject', [
'Bucket' => $targetBucket,
'Key' => "{targetKeyname}-{$i}",
'CopySource' => "{$sourceBucket}/{$sourceKeyname}",
]);
}
try {
$results = CommandPool::batch($s3, $batch);
foreach($results as $result) {
if ($result instanceof ResultInterface) {
// Result handling here
}
if ($result instanceof AwsException) {
// AwsException handling here
}
}
} catch (\Exception $e) {
// General error handling here
}
憑證引數也可以在創建 S3Client 物件的程序中傳遞,如下所示:
$s3 = new S3Client([
'version' => 'latest',
'region' => 'us-east-1',
'credentials' => [
'key' => '**client key**',
'secret' => '**client secret**',
],
]);
uj5u.com熱心網友回復:
這是一個執行檔案復制的函式,存盤桶到存盤桶:
function s3toS3FileCopy($sourceBucket, $sourceFilePath, $targetBucket, $targetFilePath) {
$env = getenv();
$s3 = new S3Client([
'version' => 'latest',
'region' => 'eu-central-1',
'credentials' => [
'key' => $env['S3_ACCESS_KEY'],
'secret' => $env['S3_SECRET_KEY'],
],
]);
$s3->copyObject([
'Bucket' => $targetBucket,
'Key' => $targetFilePath,
'CopySource' => "{$sourceBucket}/{$sourceFilePath}",
]);
}
如果使用其他方式,可以跳過“憑據”引數陣列。還要設定您需要的區域引數。不支持在不同區域之間復制。這很簡單,但引數并不那么直觀。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/378538.html
