AwsS3.php 11 KB

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