[英]How to upload file directly to AWS S3 with AWS SDK?
I want to upload image files directly to S3 without storing them on my server (for security). 我想直接将图像文件上传到S3,而不将它们存储在服务器上(出于安全性考虑)。 How can I do that with the PHP SDK from AWS S3?
如何使用AWS S3的PHP SDK做到这一点? here is an example code:
这是一个示例代码:
<?php
require_once '/var/www/site/vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
$bucket = '<your bucket name>';
$keyname = 'sample';
$filepath = '/path/to/image.jpg';
// Instantiate the client.
$s3 = S3Client::factory(array(
'key' => 'your AWS access key',
'secret' => 'your AWS secret access key'
));
try {
$result = $s3->putObject(array(
'Bucket' => $bucket,
'Key' => $keyname,
'SourceFile' => $filepath,
'ACL' => 'public-read'
));
echo 'Success';
} catch (S3Exception $e) {
echo $e->getMessage() . "\n";
}
Here is the upload form: 这是上传表格:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" id="image">
<input type="submit" value="Upload Image" name="submit">
</form>
What would I put for $filepath
in the PHP code since I don't want to store it on my server for security reason (I don't want it to execute malicious code and stuff like that)? 由于出于安全原因我不想将
$filepath
存储在服务器上,我该在$filepath
中输入什么(我不希望它执行恶意代码或类似的东西)? Any help would be appreciated thanks! 任何帮助,将不胜感激,谢谢!
PHP's built in file upload handling will make this very easy. PHP的内置文件上传处理功能将使此操作非常容易。 When a request is received with a file, PHP automatically moves it to temporary location & makes it's metadata accessible using
$_FILES
. 收到文件请求后,PHP会自动将其移动到临时位置并使用
$_FILES
使其元数据可访问。
You can then do something like below to upload the file to s3: 然后,您可以执行以下操作,将文件上传到s3:
<?php
if(empty($_FILES['image'])){
die('Image missing');
}
$fileName = $_FILES['image']['name'];
$tempFilePath = $_FILES['image']['tmp_name'];
require 'vendor/autoload.php';
$s3 = S3Client::factory(array(
'key' => 'your AWS access key',
'secret' => 'your AWS secret access key'
));
try {
$result = $s3->putObject(array(
'Bucket' => '<your bucket>',
'Key' => $fileName,
'SourceFile' => $tempFilePath,
'ACL' => 'public-read'
));
echo 'Success';
} catch (S3Exception $e) {
echo $e->getMessage() . "\n";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.