我想直接将图像文件上传到S3,而不将它们存储在服务器上(出于安全性考虑)。如何使用PHP SDK from AWS S3做到这一点?这是示例代码:
<?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";
}
这是上传表单:
<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>
我出于安全原因不想将$filepath
放在PHP代码中,因为我不想将其存储在服务器上(我不希望它执行恶意代码和类似的东西)?任何帮助将不胜感激,谢谢!
答案 0 :(得分:1)
PHP的内置文件上传处理功能使此操作非常容易。收到文件请求后,PHP会自动将其移动到临时位置并使用$_FILES
使其元数据可访问。
然后您可以执行以下操作,将文件上传到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";
}