我正在尝试使用PHP和cURL将一些文件上传到DigitalOcean的Spaces,但是由于某些原因,我无法做到这一点。我不想使用像Amazon SDK这样的库,因为它们太大了。我想要更简单的东西。 这是我现在的位置。
$file = '/home/development/www/source.png';
$contents = file_get_contents($file);
$filesize = filesize($file);
$accessKeyId = '###';
$secretKey = '###';
$longDate = gmdate('Ymd\THis\Z');
$shortDate = gmdate('Ymd');
$newfile = urlencode('/new-dir/new-file.png');
$cannonical = 'PUT'.PHP_EOL.''.$newfile.''.PHP_EOL.''.PHP_EOL.'content-length:'.$filesize.''.PHP_EOL.'host:fra1.digitaloceanspaces.com'.PHP_EOL.'x-amz-date:'.$longDate.''.PHP_EOL.'x-amz-acl:public-read'.PHP_EOL.'content-length;host;x-amz-date;x-amz-acl;'.PHP_EOL.''.hash_file('sha256', $file).''.PHP_EOL.'';
$cannonical = hash('sha256', $cannonical);
$string = 'AWS4-HMAC-SHA256'.PHP_EOL.''.$longDate.''.PHP_EOL.''.$shortDate.'/fra1/s3/aws4_request'.PHP_EOL.''.$cannonical.''.PHP_EOL.'';
$signingKey = hash_hmac('sha256', $shortDate, 'AWS4'.$secretKey, true);
$signingKey = hash_hmac('sha256', 'fra1', $signingKey, true);
$signingKey = hash_hmac('sha256', 's3', $signingKey, true);
$signingKey = hash_hmac('sha256', 'aws4_request', $signingKey, true);
$signature = hash_hmac('sha256', $signingKey.$string, $signingKey);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_URL, 'https://bucket.fra1.digitaloceanspaces.com/'.$newfile);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Length' => $filesize,
'Host' => 'bucket.fra1.digitaloceanspaces.com',
'x-amz-date' => $longDate,
'x-amz-acl' => 'public-read',
'Authorization' => 'AWS4-HMAC-SHA256 Credential='.$accessKeyId.'/'.$longDate.'/fra1/s3/aws4_request, SignedHeaders=host;x-amz-date;x-amz-acl;content-length, Signature='.$signature
]);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $contents);
curl_exec($ch);
echo curl_error($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo $http_code;
每次我尝试上传上面写着“ 403 Forbidden”的内容。很可能我没有正确生成授权,但不确定自己做错了什么。