Download.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 BaseException
  23. */
  24. public function saveTempImage(int $storeId, string $url, string $prefix = 'temp')
  25. {
  26. $savePath = $this->getSavePath($storeId, $prefix, $url);
  27. if (!file_exists($savePath)) {
  28. $result = $this->curl($url);
  29. empty($result) && throwError('获取到的图片内容为空');
  30. $this->fwrite($savePath, $result);
  31. }
  32. return $savePath;
  33. }
  34. /**
  35. * 写入文件
  36. * @param string $savePath
  37. * @param string $result
  38. * @return false|int
  39. */
  40. private function fwrite(string $savePath, string $result)
  41. {
  42. $fp = fopen($savePath, 'w');
  43. $status = fwrite($fp, $result);
  44. fclose($fp);
  45. return $status;
  46. }
  47. /**
  48. * 请求网络文件
  49. * @param string $url
  50. * @return bool|string
  51. */
  52. private function curl(string $url)
  53. {
  54. $ch = curl_init($url);
  55. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  56. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  57. curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
  58. $result = curl_exec($ch);
  59. curl_close($ch);
  60. return $result;
  61. }
  62. /**
  63. * 文件保存的路径
  64. * @param int $storeId
  65. * @param string $prefix
  66. * @param string $url
  67. * @return string
  68. */
  69. private function getSavePath(int $storeId, string $prefix, string $url)
  70. {
  71. $dirPath = $this->getDirPath($storeId);
  72. return $dirPath . '/' . $prefix . '_' . md5($url) . '.png';
  73. }
  74. /**
  75. * 文件保存的目录
  76. * @param int $storeId
  77. * @return string
  78. */
  79. private function getDirPath(int $storeId)
  80. {
  81. $dirPath = runtime_root_path() . "image/{$storeId}";
  82. !is_dir($dirPath) && mkdir($dirPath, 0755, true);
  83. return $dirPath;
  84. }
  85. }