Download.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 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 app\common\exception\BaseException;
  14. class Download
  15. {
  16. /**
  17. * 获取网络图片到临时目录
  18. * @param int $storeId
  19. * @param string $url
  20. * @param string $prefix
  21. * @return string
  22. * @throws \cores\exception\BaseException
  23. */
  24. public function saveTempImage(int $storeId, string $url, string $prefix = 'temp'): string
  25. {
  26. $savePath = $this->getSavePath($storeId, $prefix, $url);
  27. if (!file_exists($savePath)) {
  28. $result = $this->curl($url);
  29. empty($result) && throwError('获取到的图片内容为空 url: ' . $url);
  30. $this->fwrite($savePath, $result);
  31. }
  32. return $savePath;
  33. }
  34. /**
  35. * 写入文件
  36. * @param string $savePath
  37. * @param string $result
  38. */
  39. private function fwrite(string $savePath, string $result)
  40. {
  41. $fp = fopen($savePath, 'w');
  42. fwrite($fp, $result);
  43. fclose($fp);
  44. }
  45. /**
  46. * 请求网络文件
  47. * @param string $url
  48. * @return bool|string
  49. */
  50. private function curl(string $url)
  51. {
  52. $ch = curl_init($url);
  53. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  54. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  55. $result = curl_exec($ch);
  56. curl_close($ch);
  57. return $result;
  58. }
  59. /**
  60. * 文件保存的路径
  61. * @param int $storeId
  62. * @param string $prefix
  63. * @param string $url
  64. * @return string
  65. */
  66. private function getSavePath(int $storeId, string $prefix, string $url): string
  67. {
  68. $dirPath = $this->getDirPath($storeId);
  69. return $dirPath . '/' . $prefix . '_' . md5($url) . '.png';
  70. }
  71. /**
  72. * 文件保存的目录
  73. * @param int $storeId
  74. * @return string
  75. */
  76. private function getDirPath(int $storeId): string
  77. {
  78. $dirPath = runtime_root_path() . "image/{$storeId}";
  79. !is_dir($dirPath) && mkdir($dirPath, 0755, true);
  80. return $dirPath;
  81. }
  82. }