Php provides two remote image retrieval methods: CURL and sockets. For more information, see.
Php provides two remote image retrieval methods: CURL and sockets. For more information, see.
Method 1: sockets
The Code is as follows:
$ A = "http://jb51.net/content/uploadfile/201106/thum-f3ccdd27d2000e3f9255a7e3e2c4880020110622095243.jpg ";
$ Local = 'socket1.gif ';
$ Aa = getImg ($ a, $ local );
/*
* @ Complete image address
* @ Name of the file to be stored
*/
Function getImg ($ url = "", $ filename = ""){
If (is_dir (basename ($ filename ))){
Echo "The Dir was not exits ";
Return false;
}
// Remove the quotation marks above the URL Connection
$ Url = preg_replace ('/(? : ^ [\ '"] + | [\'" \/] + $)/', '', $ Url );
If (! Extension_loaded ('buckets') return false;
// Obtain url-related information
Preg_match ('/http: \/([^ \/\:] + (\: \ d })?) (. *)/I ', $ url, $ matches );
If (! $ Matches) return false;
$ Sock = socket_create (AF_INET, SOCK_STREAM, SOL_TCP );
If (! @ Socket_connect ($ sock, $ matches [1], $ matches [2]? Substr ($ matches [2], 1): 80 )){
Return false;
}
// Relative address of the image
$ Msg = 'get'. $ matches [3]. "HTTP/1.1 \ r \ n ";
// Host name
$ Msg. = 'host: '. $ matches [1]. "\ r \ n ";
$ Msg. = 'Connection: close'. "\ r \ n ";
Socket_write ($ sock, $ msg );
$ Bin = '';
While ($ tmp = socket_read ($ sock, 10 )){
$ Bin. = $ tmp;
$ Tmp = '';
}
$ Bin = explode ("\ r \ n", $ bin );
$ Img = $ bin [1];
$ H = fopen ($ filename, 'wb ');
$ Res = fwrite ($ h, $ img) = false? False: true;
@ Socket_close ($ sock );
Return $ res;
}
Method 2: curl
The Code is as follows:
$ Url = "http://jb51.net/content/uploadfile/201106/thum-f3ccdd27d2000e3f9255a7e3e2c4880020110622095243.jpg ";
$ Filename = 'curl.gif ';
// Http://jb51.net
GetImg ($ url, $ filename );
/*
* @ Obtain the specified image locally using curl
* @ Complete image address
* @ Name of the file to be stored
*/
Function getImg ($ url = "", $ filename = ""){
If (is_dir (basename ($ filename ))){
Echo "The Dir was not exits ";
Return false;
}
// Remove the quotation marks above the URL Connection
$ Url = preg_replace ('/(? : ^ [\ '"] + | [\'" \/] + $)/', '', $ Url );
$ Hander = curl_init ();
$ Fp = fopen ($ filename, 'wb ');
Curl_setopt ($ hander, CURLOPT_URL, $ url );
Curl_setopt ($ hander, CURLOPT_FILE, $ fp );
Curl_setopt ($ hander, CURLOPT_HEADER, 0 );
Curl_setopt ($ hander, CURLOPT_FOLLOWLOCATION, 1 );
// Curl_setopt ($ hander, CURLOPT_RETURNTRANSFER, false); // return data in the form of data stream. If it is false, it is directly displayed.
Curl_setopt ($ hander, CURLOPT_TIMEOUT, 60 );
/* $ Options = array (
CURLOPT_URL => 'HTTP: // response ',
CURLOPT_FILE => $ fp,
CURLOPT_HEADER => 0,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_TIMEOUT => 60
);
Curl_setopt_array ($ hander, $ options );
*/
Curl_exec ($ hander );
Curl_close ($ hander );
Fclose ($ fp );
Return true;
}
?>