通过PHP curl接收图像,然后上传到S3


Receive image via PHP curl, then upload to S3

我使用PHP CURL从REST API生成自定义PNG图像。一旦加载了这个图片,我想把它上传到AWS S3 Bucket中,并显示它的链接。

到目前为止,这是我的脚本:

$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, 'http://url-to-generate-image.com?options=' + $_GET['options']);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$info=curl_getinfo($ch);
curl_close($ch);
//require S3 Class
if (!class_exists('S3')) {
    require_once('S3.php');
}
//AWS access info
if (!defined('awsAccessKey')) {
    define('awsAccessKey', 'MY_ACCESS_KEY');
}
if (!defined('awsSecretKey')) {
    define('awsSecretKey', 'MY_SECRET_KEY');
}
//instantiate the class
$s3 = new S3(awsAccessKey, awsSecretKey);
$s3->putBucket('bucket-name', S3::ACL_PUBLIC_READ);
$file_name = md5(rand(99,99999999)) + '-myImage.png';
if ($s3->putObjectFile($data, 'bucket-name' , $file_name, S3::ACL_PUBLIC_READ)) {
    echo 'success';
    $gif_url = 'http://bucket-name.s3.amazonaws.com/'.$file_name;
} else {
    echo 'failed';
}

它不断失败。现在,我认为问题在于我在哪里使用putObjectFile——$data变量表示图像,但也许它必须以另一种方式传递?

我为S3使用了一个通用的PHP类:http://undesigned.org.za/2007/10/22/amazon-s3-php-class

使用PHP内存包装器来存储图像的内容,并使用$s3->putObject()方法:

$fp = fopen('php://memory', 'wb');
fwrite($fp, $data);
rewind($fp);
$s3->putObject([
    'Bucket' => $bucketName,
    'Key' => $fileName,
    'ContentType' => 'image/png',
    'Body' => $fp,
]);
fclose($fp);

使用PHP 5.5和最新的AWS库验证的方法(您可能需要稍微更改代码)。

http://php.net/manual/en/wrappers.php.php