Amazon AWS S3 is a robust storage solution for the internet. It can be used to store and retrieve any amount of data, at any time, from anywhere on the web. With S3 you get access to highly scalable, reliable, secure, fast, inexpensive infrastructure for your web app.
Amazon AWS S3是一个强大的互联网存储解决方案。 它可用于随时随地从网络上的任何地方存储和检索任意数量的数据。 使用S3,您可以访问Web应用程序的高度可扩展,可靠,安全,快速,廉价的基础结构。
In the coming weeks I’ll be creating a series of tutorials that show you how to do amazing things using Amazon S3 and other Amazon AWS services. This article is designed to give you a running start in using Amazon Web Services.
在接下来的几周中,我将创建一系列教程,向您展示如何使用Amazon S3和其他Amazon AWS服务来完成令人惊奇的事情。 本文旨在为您提供一个开始使用Amazon Web Services的开始。
Amazon has provided powerful SDK support for many different platforms, including PHP. In this article you’ll learn how to start using the AWS SDK for PHP using practical examples.
亚马逊为许多不同的平台(包括PHP)提供了强大的SDK支持。 在本文中,您将通过实际示例学习如何开始使用适用于PHP的AWS开发工具包。
Most web hosts have a PHP setup that will support the SDK without any additional configuration, but if you have any trouble with any of the examples below, please see the Resources at the end of this article.
大多数Web主机都有一个PHP安装程序,无需任何其他配置即可支持SDK,但是如果您对以下任何示例有任何疑问,请参阅本文结尾处的参考资料。
In addition to a regular old web host, you’ll also need an Amazon AWS account. Set one up at: http://aws.amazon.com
除了常规的旧网络主机之外,您还需要一个Amazon AWS帐户。 在以下网址设置一个: http : //aws.amazon.com
Also, you’ll need to make sure you have the Amazon AWS S3 service enabled in your account. All of my examples will utilize that service.
另外,您需要确保您的帐户中启用了Amazon AWS S3服务。 我所有的示例都将利用该服务。
1) Download Start by getting the SDK files on your web server. There are a few ways to accomplish this. My favorite is to download the SDK and upload the files to your web server. Easy, right? You can also use PEAR and a few other methods to install the SDK. You can download the latest version here: http://pear.amazonwebservices.com/get/sdk-latest.zip
1)下载首先在Web服务器上获取SDK文件。 有几种方法可以完成此操作。 我最喜欢的是下载SDK并将文件上传到您的Web服务器。 容易吧? 您还可以使用PEAR和其他一些方法来安装SDK。 您可以在此处下载最新版本: http : //pear.amazonwebservices.com/get/sdk-latest.zip
For the purposes of this article, I’m going to upload the SDK to a folder in the root of my web called “awssdk”.
出于本文的目的,我将把SDK上载到Web根目录下的文件夹“ awssdk”。
2) Rename the Config File
2)重命名配置文件
Once your files are uploaded, you need to update your configuration file. The first step is to change the name of the config file from config-sample.inc.php to: config.inc.php
文件上传后,您需要更新配置文件。 第一步是将配置文件的名称从config-sample.inc.php更改为: config.inc.php
3) Config File Settings Now open the config file and insert your own credentials. There 10 or more constants being defined in this file. For now you only need to update three of them:
3)配置文件设置现在打开配置文件并插入您自己的凭据。 该文件中定义了10个或更多的常量。 现在,您只需要更新其中三个即可:
define('AWS_KEY', 'ENTER YOUR AWS KEY HERE');
define('AWS_SECRET_KEY', 'ENTER YOUR AWS SECRET KEY HERE');
define('AWS_ACCOUNT_ID', 'ENTER YOUR AWS ACCOUNT ID HERE');
Finding these values is easy:
查找这些值很容易:
Start by creating a file called fun.php in the same folder where I uploaded the SDK. So far, here’s what your directory structure should look like:
首先在我上传SDK的文件夹中创建一个名为fun.php的文件。 到目前为止,目录结构应如下所示:
/awssdk/sdk.class.php
/awssdk/config.inc.php
/awssdk/fun.php
/awssdk/utilities
/awssdk/services
/awssdk/lib
/awssdk/extensions
/awssdk/.... (a few more directories)
We’ll be doing all our coding in fun.php
我们将在fun.php中进行所有编码
1) Include the AWS SDK
1)包括AWS开发工具包
In order to use the SDK, it needs to be included in our PHP code. If you setup your file structure like I demonstrated above, the following code should work to include the SDK:
为了使用SDK,它必须包含在我们PHP代码中。 如果像我上面演示的那样设置文件结构,则以下代码应该可以包含SDK:
<?php
require_once 'sdk.class.php';
2) Create a Bucket
2)创建一个存储桶
The easiest test you can do in the AWS SDK is to create a bucket in S3. An S3 bucket is like a “domain” for file storage. Once we have a bucket we can start creating, editing, and deleting files using PHP. Here’s the code:
您可以在AWS开发工具包中执行的最简单的测试是在S3中创建存储桶。 S3存储桶就像文件存储的“域”。 一旦有了存储桶,就可以开始使用PHP创建,编辑和删除文件。 这是代码:
<?php
require_once 'sdk.class.php';
// Create the s3 Object from the SDK
$s3 = new AmazonS3();
// Run the Method: Create Bucket.
// Arg 1: 'my-unique-bucket-name' is the name of your new bucket.
// Arg 2: The geographical region where your data will be stored.
// Arg 3: Tells Amazon to make your files readable by anyone like regular files hosted on a web server.
$response = $s3->create_bucket('my-unique-bucket-name', AmazonS3::REGION_US_E1, AmazonS3::ACL_PUBLIC);
// The response comes back as a Simple XML Object
// In this case we just want to know if everything was okay.
// If not, report the message from the XML response.
if ((int) $response->isOK()) {
echo 'Created Bucket';
} else {
echo (string) $response->body->Message;
}
Here are few things to remember when creating S3 buckets:
创建S3存储桶时,需要记住以下几点:
2) List Buckets
2)清单桶
Now that you’ve created a bucket, you can use the following example to list all the buckets in your account:
现在,您已经创建了存储桶,可以使用以下示例列出帐户中的所有存储桶:
<?php
$s3 = new AmazonS3();
$response = $s3->list_buckets();
foreach ($response->body->Buckets[0] as $bucket) {
echo (string) $bucket->Name."<br />";
}
Now that we have a bucket, we’re ready to take on the world. The following example demonstrates how to create simple text file in an AWS bucket:
现在我们有了一个水桶,我们已经准备好迎接这个世界。 以下示例演示了如何在AWS存储桶中创建简单的文本文件:
<?php
require_once 'sdk.class.php';
$s3 = new AmazonS3();
// Create Object is pretty self explanatory:
// Arg 1: The bucket where your file will be created.
// Arg 2: The name of your file.
// Arg 3: An array of Options.
// In this case we're specifying the "body" option
// and the ACL setting to allow this file to be read by anyone.
$response = $s3->create_object('my-unique-bucket-name', 'test1.txt', array(
'body' => 'Hello world. Nice to meet you.',
'acl'=>AmazonS3::ACL_PUBLIC,
));
if ((int) $response->isOK()) echo 'I Created a File!';
To test if your file uploaded, try accessing it using its URL: http://your-unique-bucket-name-here.s3.amazonaws.com/test1.txt
要测试文件是否上传,请尝试使用其URL访问它:http://your-unique-bucket-name-here.s3.amazonaws.com/test1.txt
The most basic usage for Amazon’s S3 service is to provide storage and delivery for web content like images, videos, and other media. You can serve any kind of content using S3, including streaming video and regular HTML web pages. Amazon handles all the working of making sure your files are safe and that they are always delivered fast, all you need to do is get your files into an S3 bucket! We’ve already demonstrated how to create a simple text file in S3. The following examples demonstrate a few additional options for getting files up into your S3 bucket:
Amazon S3服务的最基本用法是为图像,视频和其他媒体等Web内容提供存储和交付。 您可以使用S3提供任何类型的内容,包括流视频和常规HTML网页。 Amazon负责确保您的文件安全并始终快速交付文件的所有工作,您要做的就是将文件放入S3存储桶! 我们已经演示了如何在S3中创建一个简单的文本文件。 以下示例演示了一些用于将文件上传到S3存储桶的其他选项:
1) Upload a File from Your Server
1)从您的服务器上传文件
For this example, upload a file called “file.jpg” into your awssdk folder. Our goal is to upload the file from your server to the S3 bucket:
在此示例中,将名为“ file.jpg”的文件上载到awssdk文件夹中。 我们的目标是将文件从您的服务器上传到S3存储桶:
<?php
require_once 'sdk.class.php';
$s3 = new AmazonS3();
// Create Object is pretty self explanatory:
// Arg 1: The bucket where your file will be created.
// Arg 2: The name of your file.
// Arg 3: An array of Options.
// In this case we're specifying the "fileUpload" option (a file on your server)
// and the ACL setting to allow this file to be read by anyone.
$response = $s3->create_object('my-unique-bucket-name', 'in_the_cloud.jpg', array(
'fileUpload'=>__DIR__.'/file.jpg',
'acl'=>AmazonS3::ACL_PUBLIC,
));
// Check if everything is okay.
if ((int) $response->isOK()) echo 'I Uploaded a File from My Server!';
As with the previous example, you can verify your upload by previewing it in your browser: http://my-unique-bucket-name-here.s3.amazonaws.com/in_the_cloud.jpg
与前面的示例一样,您可以通过在浏览器中预览上传来验证上传的内容:http://my-unique-bucket-name-here.s3.amazonaws.com/in_the_cloud.jpg
2) Upload a File from Another Website
2)从另一个网站上传文件
Sometimes you want to get a file from another URL into S3. This is really easy:
有时您想将文件从另一个URL导入S3。 这真的很简单:
<?php
require_once 'sdk.class.php';
$s3 = new AmazonS3();
// Create Object is pretty self explanatory:
// Arg 1: The bucket where your file will be created.
// Arg 2: The name of your file.
// Arg 3: An array of Options.
// In this case we're specifying the "body" option (opening a file from the web),
// we're setting the contentType of the file so browsers know its an image,
// and we're setting the ACL setting to allow this file to be read by anyone.
$response = $s3->create_object('my-unique-bucket-name', 'from_a_url.gif', array(
'body'=>file_get_contents('http://www.google.com/logos/logo_newyear.gif'),
'contentType'=>'image/gif',
'acl'=>AmazonS3::ACL_PUBLIC,
));
// Check if everything is okay.
if ((int) $response->isOK()) echo 'I Uploaded a File from the Web!';
2) Generate a Thumbnail Let’s say you want to generate a thumbnail from an image and you know the URL of the image. This example will work:
2)生成缩略图假设您要从图像生成缩略图,并且知道图像的URL。 这个例子可以工作:
<?php
require_once 'sdk.class.php';
$s3 = new AmazonS3();
// Create a thumbnail from a URL
$originalImage = imagecreatefromgif('http://www.google.com/logos/logo_newyear.gif');
$new_height = 30;
$width = imagesx($originalImage);
$height = imagesy($originalImage);
$new_width = round(($width * $new_height) / $height);
$imageResized = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($imageResized, $originalImage, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
// Save the image in a temp file.
$tempfilename = tempnam(__DIR__, "newImage");
ImageJpeg($imageResized,$tempfilename,100);
// Create Object is pretty self explanatory:
// Arg 1: The bucket where your file will be created.
// Arg 2: The name of your file.
// Arg 3: An array of Options.
// In this case we're specifying the "body" option (opening the temp image file we created),
// we're setting the contentType of the file so browsers know its an image,
// and we're setting the ACL setting to allow this file to be read by anyone.
$response = $s3->create_object('my-unique-bucket-name', 'from_php_script.jpg', array(
'body'=>file_get_contents($tempfilename),
'contentType'=>'image/jpeg',
'acl'=>AmazonS3::ACL_PUBLIC,
));
// Delete the temporary file.
unlink($tempfilename);
// Check if everything is okay.
if ((int) $response->isOK()) echo 'I Uploaded a File Created with PHP!';
In some cases, you want to add a little bit of security to the images your store on S3. S3 provides a number of ways to add security, but one of the easiest ways is to generate time-limited URLs.
在某些情况下,您希望为S3上存储的图像增加一点安全性。 S3提供了多种增加安全性的方法,但是最简单的方法之一就是生成时间受限的URL。
Time-limited URLs are easy to generated, and they allow you to allow your users to download content using a secure URL that will expire as soon as you want it to. In some cases, you might want your content to expire within a few minutes. This works great for showing protected images on a website. In other cases you might want to allow the file to be downloaded for a few days or weeks, which may work better for delivering links to downloads by email.
限时URL易于生成,它们使您可以允许用户使用安全URL下载内容,该URL会在您希望的时候立即过期。 在某些情况下,您可能希望内容在几分钟内过期。 这非常适合在网站上显示受保护的图像。 在其他情况下,您可能希望将文件下载几天或几周,这样可能更适合通过电子邮件传递下载链接。
The first step in creating a secure file, is to upload a file that cannot be accessed by default on the internet:
创建安全文件的第一步是上传默认情况下无法在Internet上访问的文件:
<?php
require_once 'sdk.class.php';
$s3 = new AmazonS3();
// Create Object is pretty self explanatory:
// Arg 1: The bucket where your file will be created.
// Arg 2: The name of your file.
// Arg 3: An array of Options.
// In this case we're specifying the "fileUpload" option (a file on your server)
// and the ACL setting to prevent this file from being read by anyone on the interent.
$response = $s3->create_object('my-unique-bucket-name', 'in_the_cloud_private.jpg', array(
'fileUpload'=>__DIR__.'/file.jpg',
'acl'=>AmazonS3::ACL_PRIVATE,
));
// Check if everything is okay.
if ((int) $response->isOK()) echo 'I Uploaded a PRIVATE File from My Server!';
The regular URL for this file would be: http://my-unique-bucket-name.s3.amazonaws.com/in_the_cloud_private.jpg
该文件的常规URL为:http://my-unique-bucket-name.s3.amazonaws.com/in_the_cloud_private.jpg
But if you try that URL, you’ll get an access denied error. This is good because we want this file to be protected. But let’s say we wanted to send a link to this file to someone by email. We want to make it easy for them to download, but we don’t want that link to get out on some forum somewhere where it can be downloaded anytime by anyone. The solution is to create a link to the file that expires in 24 hours. Here’s how easy it is:
但是,如果您尝试使用该URL,则会收到拒绝访问错误。 这很好,因为我们希望该文件受到保护。 但是,假设我们想通过电子邮件将指向该文件的链接发送给某人。 我们希望使他们易于下载,但我们不希望该链接出现在某个论坛上,任何人都可以随时下载。 解决方案是创建指向24小时后失效的文件的链接。 这很简单:
<?php
require_once 'sdk.class.php';
$s3 = new AmazonS3();
//Generate a Secure URL
$secureURl = $s3->get_object_url(
'my-unique-bucket-name',
'in_the_cloud.jpg',
'24 Hours'
);
echo $secureURl;
This will generate a URL that looks like this: http://my-unique-bucket-name.s3.amazonaws.com/in_the_cloud.jpg?AWSAccessKeyId=AKIAINUIRH7EHMGFBWQQ&Expires=1313027791&Signature=G2IlL3fWpi0MyvDcuplbNeF2uNg%3D
这将生成如下所示的URL:http://my-unique-bucket-name.s3.amazonaws.com/in_the_cloud.jpg?AWSAccessKeyId=AKIAINUIRH7EHMGFBWQQ&Expires=1313027791&Signature=G2IlL3fWpi0MyvDcuplbNeF2uNg%3D
This link will provide access to the file for 24 hours, after that the user will get an Access Denied error.
此链接将提供对文件的访问24小时,此后用户将收到“访问被拒绝”错误。
Hopefully after trying these examples you feel comfortable creating and accessing files using Amazon’s S3 storage service.
希望在尝试完这些示例后,您可以轻松使用Amazon的S3存储服务创建和访问文件。
We’ve only scratched the surfaces of what is possible. In the coming weeks I’ll take you deeper into many of the ways you can use S3 to do amazing things with your websites and web applications.
我们只是刮擦了一切可能的表面。 在接下来的几周中,我将带您更深入地了解使用S3在网站和Web应用程序上完成令人惊奇的事情的许多方法。
If you have questions or suggestions about using S3 as I’ve described, please open a discussion below!
如果您对我所说的使用S3有任何疑问或建议,请在下面进行讨论!
Image via Kentoh / Shutterstock
图片来自Kentoh / Shutterstock
翻译自: https://www.sitepoint.com/getting-started-with-the-aws-php-sdk/