Upload/download processing to S3 using "AWS SDK for PHP v3"
Hello.
I'm Mandai, in charge of Wild on the development team.
If you google it, you can find a lot about "AWS SDK for PHP", but there are still many articles on v2, and the command system has changed a lot, so if you copy the sutra as is, it won't work properly! (It's me)
This time, we will provide a sample of uploading and downloading to S3 using "AWS SDK for PHP v3".
menu
AWS settings
First, before we start writing the code, we will configure the AWS side.
Create an S3 bucket and optionally set up dedicated IAM for security purposes.
Create S3 bucket
the S3 page by clicking the "Create Bucket" button.
name and region
bucket name
The bucket name is also listed on the screen, and it says ``Enter a DNS-compliant bucket name.''
What is DNS compliance?
- Contains only alphanumeric characters, hyphens, and dots (underscores are not allowed)
- Number of characters is between 3 and 63 characters
- Does not end with a hyphen or a dot
- Hyphens and dots are not consecutive to each other (“.-”, “-.”)
- Dots are not consecutive ("..", "...")
- First character must be alphanumeric
It's like.
If you use dots to separate characters and perform SSL communication using the subdomain format, an SSL certificate warning will appear.
I think it's best to avoid using dots as much as possible.
region
For Region, select the region where you want to store your data.
If the service is for Japan, it is better to select "ap-northeast-1" (Tokyo).
Copy configuration from existing bucket
If you want to use the same settings as other buckets, select here.
Setting properties
Once you have set the name and region, you can create a bucket, but you can also use S3 even more intelligently by enabling features such as access control, version control, and logging.
Versioning
Ensure that uploaded files are versioned.
Logging
This is a setting to output access history to a log.
The function itself can be used for free, but since log files are stored in S3, S3 storage fees will naturally apply.
Data transfer fees will also be charged when viewing logs.
Tags
You can set a tag that is linked to billing information.
Using this feature, you can have separate invoices for usage fees for S3 objects configured within the same account.
Setting permissions
You can set who can access it and the public range.
Manage users
Set the users who can operate the bucket.
This user is associated with your AWS account and must be created using IAM.
Manage public permissions
An example of checking if everyone can read it is when you place static files on your site.
Do not check the public access option for buckets where you plan to store PDFs containing personal information or important Excel sheets.
As you will see later, when generating a time-limited URL, you do not need to set public access permissions, so don't worry about it and proceed.
This completes the creation of the S3 bucket.
IAM settings
When accessing from PHP, you need to write the access key and secret key in the source code configuration file.
It would be a bad idea to set an access key that can do anything, so create a user who can only access the S3 bucket you set up this time, and use that user to perform operations on S3.
First, open the IAM user creation screen and enter the following.
In the next step, you will set access privileges, but for now, proceed to the confirmation screen without setting anything.
A warning will appear saying "This user does not have access privileges", but ignore it and press the "Create user" button to complete the creation.
A CSV file containing access information will be sent via email. Alternatively, you can download the CSV file using the download button on the screen and keep it at hand.
Next, from the user list, click the username you just created to display the overview page.
Set the policy from "Add inline policy".
- Select "Amazon S3" for AWS service
- The action includes GetObject
- Enter the S3 bucket ARN with "/*" appended to the Amazon resource name.
- If you register the "Add statement" button, it will be added below.
The image below is obtained by repeating the above steps for "PutObject" and adding two statements.
Once completed, press the "Next Step" button to move to the confirmation screen.
Give the policy an easy-to-understand name and check the policy (it's probably fine, but check the ARN).
Click Validate Policy to confirm that this policy is valid. ” appears, click Apply Policy to complete.
PHP preparation
We are finally ready to write PHP code, but the last thing we need to do is install the AWS SDK for PHP.
This time I installed it from composer, so I will post the steps for that.
If you have a clean environment, just run the install normally and you're done.
composer install aws/aws-sdk-php
If you are in an environment where various setups have already been completed via composer, there is a subcommand called require, so use that instead of modifying composer.json.
composer require aws/aws-sdk-php
The latest AWS SDK for PHP is now installed.
Upload processing (local → S3)
To operate S3 from PHP, use the S3Client class.
# Pattern for creating a client object from the S3Client class $s3client = new Aws\S3\S3Client([ 'credentials' => [ 'key' => 'your access key', 'secret' => 'your access secret', ] , 'region' => 'ap-northeast-1', 'version' => 'latest', ]); # Pattern for creating a client object from the factory() method of the S3Client class $s3client = S3Client::factory([ 'credentials' => [ 'key' => 'your access key', 'secret' => 'your access secret', ], 'region' => 'ap-northeast-1', 'version' => 'latest ', ]);
There are two ways to create a client object, both of which can be handled in the same way.
Next is the main upload process.
Use the putObject() method.
$result = $s3client->putObject([ 'Bucket' => 'your bucket name', 'Key' => 'file key', 'SourceFile' => '/path/to/file', 'ContentType' => mime_content_type('/path/to/file'), ]);
If the upload is successful, the Aws\Result class is returned in $result.
This is packed with information about the S3 object you created.
Download processing (S3 → local)
Now, I would like to try downloading instead.
First, create an S3 client.
$s3client = new Aws\S3\S3Client([ 'credentials' => [ 'key' => 'your access key', 'secret' => 'your access secret', ], 'region' => 'ap-northeast -1', 'version' => 'latest', ]);
After that, as you might have guessed, we retrieve the file using the getObject() method.
$result = $s3client->getObject([ 'Bucket' => 'your bucket name', 'Key' => 'bucket key', ]);
If the download is successful, the Aws\Result class is returned in $result.
Generating an expired URL (expired url)
S3 allows you to create a URL with download settings.
This feature allows you to download important files without making them public.
This is a function also used in ChatWork, and files uploaded to a chat group are downloaded using this mechanism.
This implementation is also very easy, and although the steps are slightly different, it is done in the same way via S3client.
$cmd = $s3client->getCommand('GetObject', [ 'Bucket' => \Config::get('file.s3.bucket'), 'Key' => $file->path, ]); $result = $s3client->createPresignedRequest($cmd, '+30 seconds');
The getCommand() method converts the behavior of the process getObject() into a command and passes it to the createPresignedRequest() method.
The second argument of the createPresignedRequest() method can be set in three types: Datetime class, timestamp, and a string that can be interpreted by the strtotime() function.
Also, the expiration date cannot be set for more than one week, and the maximum expiration date is one week.
If you access a link that has passed its expiration date, a screen like the one below will be displayed and you will no longer be able to access the object.
summary
The AWS SDK for PHP is easy to install and has a class system that is easy to use, but there are bound to be differences depending on the version, such as missing methods or different arguments, so I hope this article will help you with your development. .
That's it.