PHP下載/採集遠程圖片到本地

來源:互聯網
上載者:User
  1. /**
  2. * 下載遠程圖片到本地
  3. *
  4. * @param string $url 遠程檔案地址
  5. * @param string $filename 儲存後的檔案名稱(為空白時則為隨機產生的檔案名稱,否則為原檔案名稱)
  6. * @param array $fileType 允許的檔案類型
  7. * @param string $dirName 檔案儲存的路徑(路徑其餘部分根據時間系統自動產生)
  8. * @param int $type 遠程擷取檔案的方式
  9. * @return json 返迴文件名、檔案的儲存路徑
  10. * @author blog.snsgou.com
  11. */
  12. function download_image($url, $fileName = '', $dirName, $fileType = array('jpg', 'gif', 'png'), $type = 1)
  13. {
  14. if ($url == '')
  15. {
  16. return false;
  17. }
  18. // 擷取檔案原檔案名稱
  19. $defaultFileName = basename($url);
  20. // 擷取檔案類型
  21. $suffix = substr(strrchr($url, '.'), 1);
  22. if (!in_array($suffix, $fileType))
  23. {
  24. return false;
  25. }
  26. // 設定儲存後的檔案名稱
  27. $fileName = $fileName == '' ? time() . rand(0, 9) . '.' . $suffix : $defaultFileName;
  28. // 擷取遠程檔案資源
  29. if ($type)
  30. {
  31. $ch = curl_init();
  32. $timeout = 30;
  33. curl_setopt($ch, CURLOPT_URL, $url);
  34. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  35. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  36. $file = curl_exec($ch);
  37. curl_close($ch);
  38. }
  39. else
  40. {
  41. ob_start();
  42. readfile($url);
  43. $file = ob_get_contents();
  44. ob_end_clean();
  45. }
  46. // 設定檔案儲存路徑
  47. //$dirName = $dirName . '/' . date('Y', time()) . '/' . date('m', time()) . '/' . date('d', time());
  48. $dirName = $dirName . '/' . date('Ym', time());
  49. if (!file_exists($dirName))
  50. {
  51. mkdir($dirName, 0777, true);
  52. }
  53. // 儲存檔案
  54. $res = fopen($dirName . '/' . $fileName, 'a');
  55. fwrite($res, $file);
  56. fclose($res);
  57. return array(
  58. 'fileName' => $fileName,
  59. 'saveDir' => $dirName
  60. );
  61. }
複製代碼
PHP
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.