AwsS3.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. if($website=='wigginshair'){
  86. $this->bucket ='wiggins-images';
  87. $link ='https://cdn.wigginshair.com';
  88. }
  89. if($website=='asteriawigs'){
  90. $this->bucket ='asteria-images';
  91. $link ='https://cdn.asteriahair.com';
  92. }
  93. try {
  94. // 处理文件
  95. if ($file instanceof File) {
  96. $filePath = $file->getRealPath();
  97. $fileContent = file_get_contents($filePath);
  98. $mimeType = $file->getMime();
  99. } elseif (is_string($file) && file_exists($file)) {
  100. $fileContent = file_get_contents($file);
  101. $mimeType = mime_content_type($file);
  102. } else {
  103. $fileContent = $file;
  104. $mimeType = $options['mime_type'] ?? 'application/octet-stream';
  105. }
  106. // 生成存储 key
  107. if (empty($key)) {
  108. $key = $this->generateKey($file);
  109. }
  110. // 准备请求
  111. $method = 'PUT';
  112. $uri = '/' . $key;
  113. $url = 'https://' . $this->bucket . '.s3.' . $this->region . '.amazonaws.com' . $uri;
  114. $urls = $link . $uri;
  115. $headers = [
  116. 'Host' => $this->bucket . '.s3.' . $this->region . '.amazonaws.com',
  117. 'Content-Type' => $mimeType,
  118. 'Content-Length' => strlen($fileContent),
  119. 'x-amz-content-sha256' => hash('sha256', $fileContent),
  120. 'x-amz-date' => gmdate('Ymd\THis\Z'),
  121. ];
  122. // 添加额外头部
  123. if (!empty($options['headers'])) {
  124. $headers = array_merge($headers, $options['headers']);
  125. }
  126. // 生成签名
  127. $headers['Authorization'] = $this->generateSignature($method, $uri, $headers, $fileContent);
  128. // 发送请求
  129. $response = $this->client->request($method, $url, [
  130. 'headers' => $headers,
  131. 'body' => $fileContent,
  132. ]);
  133. if ($response->getStatusCode() == 200) {
  134. return [
  135. 'success' => true,
  136. 'key' => $key,
  137. 'url' => $urls,
  138. 'size' => strlen($fileContent),
  139. 'type' => $mimeType
  140. ];
  141. } else {
  142. throw new Exception('上传失败,状态码: ' . $response->getStatusCode());
  143. }
  144. } catch (\Exception $e) {
  145. return [
  146. 'success' => false,
  147. 'msg' => '上传失败: ' . $e->getMessage(),
  148. 'error' => $e->getMessage()
  149. ];
  150. }
  151. }
  152. /**
  153. * 生成存储路径 key
  154. */
  155. protected function generateKey($file)
  156. {
  157. $config = $this->config['upload'];
  158. $savePath = $config['save_path'];
  159. // 替换路径变量
  160. $replace = [
  161. '{year}' => date('Y'),
  162. '{mon}' => date('m'),
  163. '{day}' => date('d'),
  164. '{hour}' => date('H'),
  165. '{min}' => date('i'),
  166. '{sec}' => date('s'),
  167. '{random}' => mt_rand(1000, 9999),
  168. '{uniqid}' => uniqid(),
  169. '{timestamp}'=> time(),
  170. ];
  171. $savePath = str_replace(array_keys($replace), array_values($replace), $savePath);
  172. // 生成文件名
  173. // 获取原始文件名和扩展名
  174. $originalName = $file->getInfo('name'); // 原始文件名,如 "image.jpg"
  175. $originalExtension = pathinfo($originalName, PATHINFO_EXTENSION);
  176. // 如果原始扩展名有效,使用它
  177. if (!empty($originalExtension) && strlen($originalExtension) <= 6) {
  178. $extension = strtolower($originalExtension);
  179. } else {
  180. // 否则通过内容检测
  181. $extension = $this->getRealExtensionByContent($file->getRealPath());
  182. }
  183. $sha1 = sha1($file);
  184. $filename = date('YmdHis') . '_' . substr($sha1, 0, 16) . '.' . $extension;
  185. return $savePath . $filename;
  186. }
  187. /**
  188. * 删除 S3 文件
  189. */
  190. public function delete($key)
  191. {
  192. try {
  193. $method = 'DELETE';
  194. $uri = '/' . $key;
  195. $url = 'https://' . $this->bucket . '.s3.' . $this->region . '.amazonaws.com' . $uri;
  196. $headers = [
  197. 'Host' => $this->bucket . '.s3.' . $this->region . '.amazonaws.com',
  198. 'x-amz-date' => gmdate('Ymd\THis\Z'),
  199. 'x-amz-content-sha256' => hash('sha256', ''),
  200. ];
  201. $headers['Authorization'] = $this->generateSignature($method, $uri, $headers);
  202. $response = $this->client->request($method, $url, [
  203. 'headers' => $headers,
  204. ]);
  205. return $response->getStatusCode() == 204;
  206. } catch (\Exception $e) {
  207. return false;
  208. }
  209. }
  210. /**
  211. * 检查文件是否存在
  212. */
  213. public function exists($key)
  214. {
  215. try {
  216. $method = 'HEAD';
  217. $uri = '/' . $key;
  218. $url = 'https://' . $this->bucket . '.s3.' . $this->region . '.amazonaws.com' . $uri;
  219. $headers = [
  220. 'Host' => $this->bucket . '.s3.' . $this->region . '.amazonaws.com',
  221. 'x-amz-date' => gmdate('Ymd\THis\Z'),
  222. 'x-amz-content-sha256' => hash('sha256', ''),
  223. ];
  224. $headers['Authorization'] = $this->generateSignature($method, $uri, $headers);
  225. $response = $this->client->request($method, $url, [
  226. 'headers' => $headers,
  227. ]);
  228. return $response->getStatusCode() == 200;
  229. } catch (\Exception $e) {
  230. return false;
  231. }
  232. }
  233. /**
  234. * 获取文件 URL
  235. */
  236. public function getUrl($key, $expires = 3600)
  237. {
  238. if ($expires === null) {
  239. // 公开读取的直接 URL
  240. $cdnUrl = rtrim($this->config['upload']['cdn_url'], '/');
  241. return $cdnUrl . '/' . $key;
  242. } else {
  243. // 生成预签名 URL
  244. return $this->generatePresignedUrl($key, $expires);
  245. }
  246. }
  247. /**
  248. * 生成预签名 URL
  249. */
  250. protected function generatePresignedUrl($key, $expires = 3600)
  251. {
  252. $accessKey = $this->config['credentials']['key'];
  253. $secretKey = $this->config['credentials']['secret'];
  254. $timestamp = time();
  255. $expiresAt = $timestamp + $expires;
  256. $longDate = gmdate('Ymd\THis\Z', $timestamp);
  257. $shortDate = substr($longDate, 0, 8);
  258. $service = 's3';
  259. $algorithm = 'AWS4-HMAC-SHA256';
  260. $scope = $shortDate . '/' . $this->region . '/' . $service . '/aws4_request';
  261. // 生成签名
  262. $canonicalQueryString = implode('&', [
  263. 'X-Amz-Algorithm=AWS4-HMAC-SHA256',
  264. 'X-Amz-Credential=' . urlencode($accessKey . '/' . $scope),
  265. 'X-Amz-Date=' . $longDate,
  266. 'X-Amz-Expires=' . $expires,
  267. 'X-Amz-SignedHeaders=host'
  268. ]);
  269. $canonicalRequest = implode("\n", [
  270. 'GET',
  271. '/' . $key,
  272. $canonicalQueryString,
  273. 'host:' . $this->bucket . '.s3.' . $this->region . '.amazonaws.com',
  274. '',
  275. 'host',
  276. 'UNSIGNED-PAYLOAD'
  277. ]);
  278. $stringToSign = implode("\n", [
  279. $algorithm,
  280. $longDate,
  281. $scope,
  282. hash('sha256', $canonicalRequest)
  283. ]);
  284. // 派生签名密钥
  285. $kDate = hash_hmac('sha256', $shortDate, 'AWS4' . $secretKey, true);
  286. $kRegion = hash_hmac('sha256', $this->region, $kDate, true);
  287. $kService = hash_hmac('sha256', $service, $kRegion, true);
  288. $kSigning = hash_hmac('sha256', 'aws4_request', $kService, true);
  289. $signature = hash_hmac('sha256', $stringToSign, $kSigning);
  290. $url = sprintf(
  291. 'https://%s.s3.%s.amazonaws.com/%s?%s&X-Amz-Signature=%s',
  292. $this->bucket,
  293. $this->region,
  294. $key,
  295. $canonicalQueryString,
  296. $signature
  297. );
  298. return $url;
  299. }
  300. }