if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* * 遠程擷取圖片類 * * 要求開啟curl擴充 * 類比php上傳原理,建立一個緩衝目錄,將遠程擷取的檔案存放到緩衝目錄下. * * */ class url_pic{ protected $cache; //緩衝路徑 public function __construct($cache='') { if(!emptyempty($cache)) { $this->cache = $cache; } else { $this->cache = 'uploads/cache/'; } } //設定緩衝目錄 public function set_cache($cache='') { if(!emptyempty($cache)) { $this->cache = $cache; } } /* * 擷取遠程圖片 將檔案存入cache檔案夾 * * $url 擷取遠端檔案的連結 * $error * @return 777 則返回不能建立檔案夾 * @return 存入緩衝的檔案名稱 */ public function get_file($url,$error=777) { $path = $this->build_folder($this->cache); if($path==false) return $error; $curl = curl_init(); // 設定你需要抓取的URL curl_setopt($curl, CURLOPT_URL, $url); // 設定header curl_setopt($curl, CURLOPT_HEADER, 0); // 設定cURL 參數,要求結果儲存到字串中還是輸出到螢幕上。 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 運行cURL,請求網頁 $file = curl_exec($curl); // 關閉URL請求 curl_close($curl); //將檔案寫入獲得的資料 $filename = $this->cache.date("YmdHis"); if(self::build_file($file, $filename)==false) { return false; } return $filename; } //建立檔案夾 public function build_folder($dir) { if (!is_dir($dir)) { if (!mkdir($dir,0777,TRUE) || !chmod($dir,0777)) { return false; } } return true; } /* * 移動檔案 類比php的move_uploaded_file方法 * * $cache 快取檔案路徑 * $filename 需要產生的檔案名稱的絕對路徑 * * @return $filename */ public function move_file($cache,$filename) { $file = @file_get_contents($cache); if(self::build_file($file, $filename)==false) { return false; } unlink($cache); //清除緩衝圖片 return $filename; } /* * 組建檔案 * $file 需要寫入的檔案或者二進位流 * $newname 需要產生的檔案名稱的絕對路徑 */ protected static function build_file($file,$filename) { $write = @fopen($filename,"w"); if($write==false) { return false; } if(fwrite($write,$file)==false) { return false; } if(fclose($write)==false) { return false; } return true; } }