AwsS3.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. <?php
  2. namespace app\common\library;
  3. use think\Config;
  4. use think\Exception;
  5. use think\File;
  6. use GuzzleHttp\Client;
  7. use GuzzleHttp\Psr7\Request;
  8. class AwsS3
  9. {
  10. protected $config;
  11. protected $client;
  12. protected $bucket;
  13. protected $region;
  14. public function __construct()
  15. {
  16. $this->config = Config::get('aws.s3');
  17. $this->bucket = $this->config['bucket'];
  18. $this->region = $this->config['region'];
  19. $this->client = new Client([
  20. 'timeout' => 30,
  21. 'verify' => false, // 根据环境调整
  22. ]);
  23. }
  24. /**
  25. * 生成 AWS S4 签名
  26. */
  27. protected function generateSignature($method, $uri, $headers, $payload = '')
  28. {
  29. $accessKey = $this->config['credentials']['key'];
  30. $secretKey = $this->config['credentials']['secret'];
  31. $service = 's3';
  32. $algorithm = 'AWS4-HMAC-SHA256';
  33. // 当前时间
  34. $timestamp = time();
  35. $longDate = gmdate('Ymd\THis\Z', $timestamp);
  36. $shortDate = substr($longDate, 0, 8);
  37. // 计算签名所需组件
  38. $scope = $shortDate . '/' . $this->region . '/' . $service . '/aws4_request';
  39. // 规范化请求
  40. $canonicalHeaders = '';
  41. $signedHeaders = '';
  42. ksort($headers);
  43. foreach ($headers as $key => $value) {
  44. $canonicalHeaders .= strtolower($key) . ':' . trim($value) . "\n";
  45. $signedHeaders .= strtolower($key) . ';';
  46. }
  47. $signedHeaders = rtrim($signedHeaders, ';');
  48. $canonicalRequest = implode("\n", [
  49. $method,
  50. $uri,
  51. '', // 查询字符串
  52. $canonicalHeaders,
  53. $signedHeaders,
  54. hash('sha256', $payload)
  55. ]);
  56. // 计算签名
  57. $stringToSign = implode("\n", [
  58. $algorithm,
  59. $longDate,
  60. $scope,
  61. hash('sha256', $canonicalRequest)
  62. ]);
  63. // 派生签名密钥
  64. $kDate = hash_hmac('sha256', $shortDate, 'AWS4' . $secretKey, true);
  65. $kRegion = hash_hmac('sha256', $this->region, $kDate, true);
  66. $kService = hash_hmac('sha256', $service, $kRegion, true);
  67. $kSigning = hash_hmac('sha256', 'aws4_request', $kService, true);
  68. $signature = hash_hmac('sha256', $stringToSign, $kSigning);
  69. return $algorithm . ' ' . implode(', ', [
  70. 'Credential=' . $accessKey . '/' . $scope,
  71. 'SignedHeaders=' . $signedHeaders,
  72. 'Signature=' . $signature
  73. ]);
  74. }
  75. /**
  76. * 上传文件到 S3
  77. */
  78. public function upload($file, $key = null, $options = [],$website)
  79. {
  80. $link ='https://cdn.alipearlhair.com';
  81. if($website=='alipearlhair'){
  82. $this->bucket ='alipearl-images';
  83. $link ='https://cdn.alipearlhair.com';
  84. }
  85. try {
  86. // 处理文件
  87. if ($file instanceof File) {
  88. $filePath = $file->getRealPath();
  89. $fileContent = file_get_contents($filePath);
  90. $mimeType = $file->getMime();
  91. } elseif (is_string($file) && file_exists($file)) {
  92. $fileContent = file_get_contents($file);
  93. $mimeType = mime_content_type($file);
  94. } else {
  95. $fileContent = $file;
  96. $mimeType = $options['mime_type'] ?? 'application/octet-stream';
  97. }
  98. // 生成存储 key
  99. if (empty($key)) {
  100. $key = $this->generateKey($file);
  101. }
  102. // 准备请求
  103. $method = 'PUT';
  104. $uri = '/' . $key;
  105. $url = 'https://' . $this->bucket . '.s3.' . $this->region . '.amazonaws.com' . $uri;
  106. $urls = $link . $uri;
  107. $headers = [
  108. 'Host' => $this->bucket . '.s3.' . $this->region . '.amazonaws.com',
  109. 'Content-Type' => $mimeType,
  110. 'Content-Length' => strlen($fileContent),
  111. 'x-amz-content-sha256' => hash('sha256', $fileContent),
  112. 'x-amz-date' => gmdate('Ymd\THis\Z'),
  113. ];
  114. // 添加额外头部
  115. if (!empty($options['headers'])) {
  116. $headers = array_merge($headers, $options['headers']);
  117. }
  118. // 生成签名
  119. $headers['Authorization'] = $this->generateSignature($method, $uri, $headers, $fileContent);
  120. // 发送请求
  121. $response = $this->client->request($method, $url, [
  122. 'headers' => $headers,
  123. 'body' => $fileContent,
  124. ]);
  125. if ($response->getStatusCode() == 200) {
  126. return [
  127. 'success' => true,
  128. 'key' => $key,
  129. 'url' => $urls,
  130. 'size' => strlen($fileContent),
  131. 'type' => $mimeType
  132. ];
  133. } else {
  134. throw new Exception('上传失败,状态码: ' . $response->getStatusCode());
  135. }
  136. } catch (\Exception $e) {
  137. return [
  138. 'success' => false,
  139. 'msg' => '上传失败: ' . $e->getMessage(),
  140. 'error' => $e->getMessage()
  141. ];
  142. }
  143. }
  144. /**
  145. * 生成存储路径 key
  146. */
  147. protected function generateKey($file)
  148. {
  149. $config = $this->config['upload'];
  150. $savePath = $config['save_path'];
  151. // 替换路径变量
  152. $replace = [
  153. '{year}' => date('Y'),
  154. '{mon}' => date('m'),
  155. '{day}' => date('d'),
  156. '{hour}' => date('H'),
  157. '{min}' => date('i'),
  158. '{sec}' => date('s'),
  159. '{random}' => mt_rand(1000, 9999),
  160. '{uniqid}' => uniqid(),
  161. '{timestamp}'=> time(),
  162. ];
  163. $savePath = str_replace(array_keys($replace), array_values($replace), $savePath);
  164. // 生成文件名
  165. // 获取原始文件名和扩展名
  166. $originalName = $file->getInfo('name'); // 原始文件名,如 "image.jpg"
  167. $originalExtension = pathinfo($originalName, PATHINFO_EXTENSION);
  168. // 如果原始扩展名有效,使用它
  169. if (!empty($originalExtension) && strlen($originalExtension) <= 6) {
  170. $extension = strtolower($originalExtension);
  171. } else {
  172. // 否则通过内容检测
  173. $extension = $this->getRealExtensionByContent($file->getRealPath());
  174. }
  175. $sha1 = sha1($file);
  176. $filename = date('YmdHis') . '_' . substr($sha1, 0, 16) . '.' . $extension;
  177. return $savePath . $filename;
  178. }
  179. /**
  180. * 删除 S3 文件
  181. */
  182. public function delete($key)
  183. {
  184. try {
  185. $method = 'DELETE';
  186. $uri = '/' . $key;
  187. $url = 'https://' . $this->bucket . '.s3.' . $this->region . '.amazonaws.com' . $uri;
  188. $headers = [
  189. 'Host' => $this->bucket . '.s3.' . $this->region . '.amazonaws.com',
  190. 'x-amz-date' => gmdate('Ymd\THis\Z'),
  191. 'x-amz-content-sha256' => hash('sha256', ''),
  192. ];
  193. $headers['Authorization'] = $this->generateSignature($method, $uri, $headers);
  194. $response = $this->client->request($method, $url, [
  195. 'headers' => $headers,
  196. ]);
  197. return $response->getStatusCode() == 204;
  198. } catch (\Exception $e) {
  199. return false;
  200. }
  201. }
  202. /**
  203. * 检查文件是否存在
  204. */
  205. public function exists($key)
  206. {
  207. try {
  208. $method = 'HEAD';
  209. $uri = '/' . $key;
  210. $url = 'https://' . $this->bucket . '.s3.' . $this->region . '.amazonaws.com' . $uri;
  211. $headers = [
  212. 'Host' => $this->bucket . '.s3.' . $this->region . '.amazonaws.com',
  213. 'x-amz-date' => gmdate('Ymd\THis\Z'),
  214. 'x-amz-content-sha256' => hash('sha256', ''),
  215. ];
  216. $headers['Authorization'] = $this->generateSignature($method, $uri, $headers);
  217. $response = $this->client->request($method, $url, [
  218. 'headers' => $headers,
  219. ]);
  220. return $response->getStatusCode() == 200;
  221. } catch (\Exception $e) {
  222. return false;
  223. }
  224. }
  225. /**
  226. * 获取文件 URL
  227. */
  228. public function getUrl($key, $expires = 3600)
  229. {
  230. if ($expires === null) {
  231. // 公开读取的直接 URL
  232. $cdnUrl = rtrim($this->config['upload']['cdn_url'], '/');
  233. return $cdnUrl . '/' . $key;
  234. } else {
  235. // 生成预签名 URL
  236. return $this->generatePresignedUrl($key, $expires);
  237. }
  238. }
  239. /**
  240. * 生成预签名 URL
  241. */
  242. protected function generatePresignedUrl($key, $expires = 3600)
  243. {
  244. $accessKey = $this->config['credentials']['key'];
  245. $secretKey = $this->config['credentials']['secret'];
  246. $timestamp = time();
  247. $expiresAt = $timestamp + $expires;
  248. $longDate = gmdate('Ymd\THis\Z', $timestamp);
  249. $shortDate = substr($longDate, 0, 8);
  250. $service = 's3';
  251. $algorithm = 'AWS4-HMAC-SHA256';
  252. $scope = $shortDate . '/' . $this->region . '/' . $service . '/aws4_request';
  253. // 生成签名
  254. $canonicalQueryString = implode('&', [
  255. 'X-Amz-Algorithm=AWS4-HMAC-SHA256',
  256. 'X-Amz-Credential=' . urlencode($accessKey . '/' . $scope),
  257. 'X-Amz-Date=' . $longDate,
  258. 'X-Amz-Expires=' . $expires,
  259. 'X-Amz-SignedHeaders=host'
  260. ]);
  261. $canonicalRequest = implode("\n", [
  262. 'GET',
  263. '/' . $key,
  264. $canonicalQueryString,
  265. 'host:' . $this->bucket . '.s3.' . $this->region . '.amazonaws.com',
  266. '',
  267. 'host',
  268. 'UNSIGNED-PAYLOAD'
  269. ]);
  270. $stringToSign = implode("\n", [
  271. $algorithm,
  272. $longDate,
  273. $scope,
  274. hash('sha256', $canonicalRequest)
  275. ]);
  276. // 派生签名密钥
  277. $kDate = hash_hmac('sha256', $shortDate, 'AWS4' . $secretKey, true);
  278. $kRegion = hash_hmac('sha256', $this->region, $kDate, true);
  279. $kService = hash_hmac('sha256', $service, $kRegion, true);
  280. $kSigning = hash_hmac('sha256', 'aws4_request', $kService, true);
  281. $signature = hash_hmac('sha256', $stringToSign, $kSigning);
  282. $url = sprintf(
  283. 'https://%s.s3.%s.amazonaws.com/%s?%s&X-Amz-Signature=%s',
  284. $this->bucket,
  285. $this->region,
  286. $key,
  287. $canonicalQueryString,
  288. $signature
  289. );
  290. return $url;
  291. }
  292. }