Download.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2024 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_SSL_VERIFYHOST, false);
  60. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  61. $result = curl_exec($ch);
  62. curl_close($ch);
  63. return $result;
  64. }
  65. /**
  66. * 文件保存的路径
  67. * @param int $storeId
  68. * @param string $prefix
  69. * @param string $url
  70. * @return string
  71. */
  72. private function getSavePath(int $storeId, string $prefix, string $url): string
  73. {
  74. $dirPath = $this->getDirPath($storeId);
  75. return "{$dirPath}/{$prefix}_" . md5($url) . ".png";
  76. }
  77. /**
  78. * 文件保存的目录
  79. * @param int $storeId
  80. * @return string
  81. */
  82. private function getDirPath(int $storeId): string
  83. {
  84. $dirPath = runtime_root_path() . "image/{$storeId}";
  85. !is_dir($dirPath) && mkdir($dirPath, 0755, true);
  86. return $dirPath;
  87. }
  88. }