Download.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\common\library;
  13. use cores\exception\BaseException;
  14. /**
  15. * 文件下载类
  16. * Class Download
  17. * @package app\common\library
  18. */
  19. class Download
  20. {
  21. /**
  22. * 获取网络图片到临时目录
  23. * @param int $storeId
  24. * @param string $url
  25. * @param string $prefix
  26. * @return string
  27. * @throws BaseException
  28. */
  29. public function saveTempImage(int $storeId, string $url, string $prefix = 'temp'): string
  30. {
  31. $savePath = $this->getSavePath($storeId, $prefix, $url);
  32. if (!file_exists($savePath)) {
  33. $result = $this->curl($url);
  34. empty($result) && throwError('获取到的图片内容为空 url: ' . $url);
  35. $this->fwrite($savePath, $result);
  36. }
  37. return $savePath;
  38. }
  39. /**
  40. * 写入文件
  41. * @param string $savePath
  42. * @param string $result
  43. */
  44. private function fwrite(string $savePath, string $result)
  45. {
  46. $fp = fopen($savePath, 'w');
  47. fwrite($fp, $result);
  48. fclose($fp);
  49. }
  50. /**
  51. * 请求网络文件
  52. * @param string $url
  53. * @return bool|string
  54. */
  55. private function curl(string $url)
  56. {
  57. $ch = curl_init($url);
  58. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  59. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  60. $result = curl_exec($ch);
  61. curl_close($ch);
  62. return $result;
  63. }
  64. /**
  65. * 文件保存的路径
  66. * @param int $storeId
  67. * @param string $prefix
  68. * @param string $url
  69. * @return string
  70. */
  71. private function getSavePath(int $storeId, string $prefix, string $url): string
  72. {
  73. $dirPath = $this->getDirPath($storeId);
  74. return "{$dirPath}/{$prefix}_" . md5($url) . ".png";
  75. }
  76. /**
  77. * 文件保存的目录
  78. * @param int $storeId
  79. * @return string
  80. */
  81. private function getDirPath(int $storeId): string
  82. {
  83. $dirPath = runtime_root_path() . "image/{$storeId}";
  84. !is_dir($dirPath) && mkdir($dirPath, 0755, true);
  85. return $dirPath;
  86. }
  87. }