Php remote image retrieval instance
Example: a php remote image retrieval class. Code:
- If (! Defined ('basepath') exit ('no direct script access allowed ');
- /*
- * Remote image retrieval
- *
- * Required to enable curl extension
- * Simulate the php Upload principle, create a cache directory, and store the remotely obtained files to 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 a remote image and save the file to the cache folder.
- *
- * $ Url: obtain the Remote File link
- * $ Error
- * @ Return 777: a folder cannot be created.
- * @ Return refers to the name of the file 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 want to capture
- Curl_setopt ($ curl, curlopt_url, $ url );
- // Set the header
- Curl_setopt ($ curl, curlopt_header, 0 );
- // Set the curl parameter to save the result to the string or output to the screen.
- Curl_setopt ($ curl, curlopt_returntransfer, 1 );
- // Run curl to request the webpage
- $ File = curl_exec ($ curl );
- // Close the url request
- Curl_close ($ curl );
-
- // Write the file into the 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;
- }
-
- /*
- * Simulate the move_uploaded_file method of php for mobile files
- *
- * $ Cache file path
- * $ Absolute path of the file name to be generated by 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); // clear the cached image
- Return $ filename;
- }
-
- /*
- * Generate a file
- * $ File: the file or binary stream to be written.
- * $ Absolute path of the file name to be generated for 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;
- }
- }
|