欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

PHP實現(xiàn)的下載遠程圖片自定義函數(shù)分享

 更新時間:2015年01月28日 13:02:49   投稿:junjie  
這篇文章主要介紹了PHP實現(xiàn)的下載遠程圖片自定義函數(shù)分享,本文直接給出實現(xiàn)代碼和,本文直接給出實現(xiàn)代碼和使用方法,需要的朋友可以參考下

復制代碼 代碼如下:

<?php
/**
 * PHP下載遠程圖片到本地
 *
 * @param $url string 遠程文件地址
 * @param $filename string 保存后的文件名(為空時則為隨機生成的文件名,否則為原文件名)
 * @param $fileType array 允許的文件類型
 * @param $dirName string 文件保存的路徑(路徑其余部分根據(jù)時間系統(tǒng)自動生成)
 * @param $type int 遠程獲取文件的方式
 * @return json 返回文件名、文件的保存路徑
 * @author blog.snsgou.com
 */
function getImage($url, $fileName = '', $dirName, $fileType = array('jpg', 'gif'), $type = 1)
{
 if ($url == '')
 {
  return false;
 }

 // 獲取文件原文件名
 $defaultFileName = basename($url);

 // 獲取文件類型
 $suffix = substr(strrchr($url, '.'), 1);
 if (!in_array($suffix, $fileType))
 {
  return false;
 }

 // 設置保存后的文件名
 $fileName = $fileName == '' ? time() . rand(0, 9) . '.' . $suffix : $defaultFileName;

 // 獲取遠程文件資源
 if ($type)
 {
  $ch = curl_init();
  $timeout = 15; // 超時時間
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  $file = curl_exec($ch);
  curl_close($ch);
 }
 else
 {
  ob_start();
  readfile($url);
  $file = ob_get_contents();
  ob_end_clean();
 }

 // 設置文件保存路徑
 $dirName = $dirName . '/' . date('Y', time()) . '/' . date('m', time()) . '/' . date('d', time()) . '/';
 if (!file_exists($dirName))
 {
  mkdir($dirName, 0777, true);
 }

 // 保存文件
 $res = fopen($dirName . $fileName, 'a');
 fwrite($res, $file);
 fclose($res);

 return "{'fileName':$fileName, 'saveDir':$dirName}";
}


// 舉例
// 返回:{'fileName':13668030896.jpg, 'saveDir':/www/test/img/2013/04/24/}
echo getImage('http://img.wan.renren.com/images/2013/0430/1367294093164.jpg', '', 'd:/PHP/data', array('jpg', 'gif'), 1);

相關文章

最新評論