Example, a php to get the remote image class.
Code:
-
- if ( ! defined('basepath')) exit('no direct script access allowed');
- /*
- * Remote access to image class
- *
- * Requires curl extension to be turned on
- * Simulate the PHP upload principle, create a cache directory, and store remotely obtained files in the cache directory.
- */
- class url_pic{
- protected $cache; //Cache path
-
- public function __construct($cache='')
- {
- if(!emptyempty($cache))
- {
- $this->cache = $cache;
- }
- else
- {
- $this->cache = 'uploads/cache/';
- }
- }
-
- //Set the cache directory
- public function set_cache($cache='')
- {
- if (!emptyempty($cache))
- {
- $this->cache = $cache;
- }
- }
- /*
- * Get the remote image and store the file in the cache folder
- *
- * $url Get the remote file The link
- * $error
- * @return 777 returns that the folder cannot be created
- * @return the file name stored in the cache
- */
- public function get_file($url,$error=777)
- {
- $path = $ this->build_folder($this->cache);
- if($path==false) return $error;
-
- $curl = curl_init();
- // Set the url you need to crawl
- curl_setopt($ curl, curlopt_url, $url);
- // Set header
- curl_setopt($curl, curlopt_header, 0);
- // Set curl parameters to ask whether the result is saved in a string or output to the screen.
- curl_setopt($curl, curlopt_returntransfer, 1);
- // Run curl and request the web page
- $file = curl_exec($curl);
- // Close the url request
- curl_close($curl);
-
- //Write the file Obtained data
- $filename = $this->cache.date("ymdhis");
- if(self::build_file($file, $filename)==false)
- {
- return false;
- }
- return $ filename;
- }
-
- //Create a folder
- public function build_folder($dir)
- {
- if (!is_dir($dir))
- {
- if (!mkdir($dir,0777,true) || !chmod ($dir,0777))
- {
- return false;
- }
- }
- return true;
- }
-
- /*
- * Move files to simulate PHP's move_uploaded_file method
- *
- * $cache cache file path
- * $filename required The absolute path of the generated file name
- *
- * @return $filename
- */
- public function move_file($cache,$filename)
- {
- $file = @file_get_contents($cache);
- if(self::build_file( $file, $filename)==false)
- {
- return false;
- }
- unlink($cache); //Clear cached images
- return $filename;
- }
-
- /*
- * Generate file
- * $file required The file or binary stream to be written
- * $newname is the absolute path of the file name to be generated
- */
- 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;
- }
- }
Copy code
|