Home > Backend Development > PHP Tutorial > PHP download/collect remote images to local

PHP download/collect remote images to local

WBOY
Release: 2016-07-25 08:42:33
Original
977 people have browsed it
  1. /**
  2. * Download remote images to local
  3. *
  4. * @param string $url remote file address
  5. * @param string $filename saved file name (if empty, it is a randomly generated file name, otherwise it is the original file name)
  6. * @param array $fileType Allowed file types
  7. * @param string $dirName The path where the file is saved (the rest of the path is automatically generated based on the time system)
  8. * @param int $type The way to obtain the file remotely
  9. * @return json Returns the file name , file saving path
  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. // Get the original file name of the file
  19. $defaultFileName = basename($url);
  20. // Get the file type
  21. $suffix = substr(strrchr($url, '.'), 1);
  22. if (!in_array($suffix, $fileType))
  23. {
  24. return false;
  25. }
  26. // Set the saved file name
  27. $fileName = $fileName == '' ? time() . rand(0, 9) . '.' . $suffix : $defaultFileName;
  28. // Get remote file resources
  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. // Set file saving Path
  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. // Save the file
  54. $res = fopen($dirName . '/' . $fileName, 'a');
  55. fwrite($res, $file);
  56. fclose($res);
  57. return array (
  58. 'fileName' => $fileName,
  59. 'saveDir' => $dirName
  60. );
  61. }
Copy code

PHP


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template