PHP download remote picture and save to local method summary _php instance

Source: Internet
Author: User
Tags auth flush fread php download trim

1. Get the remote file size and information function

function GetFileSize ($url) { 
$url = Parse_url ($url); 
if ($fp = @fsockopen ($url [' Host '],empty ($url [' Port ']): $url [' Port '], $error)] { 
fputs ($fp, "get". Empty ($url [' path '])? ' /': $url [' path ']]. " Http/1.1\r\n "); 
Fputs ($FP, "Host: $url [host]\r\n\r\n"); 
while (!feof ($fp)) { 
$tmp = fgets ($fp); 
if (Trim ($tmp) = = ") {break 
; 
} else if (Preg_match ('/content-length: (. *)/si ', $tmp, $arr)) {return 
trim ($arr [1]); 
} 
return null; 
} else{return 
null; 
} 
Echo GetFileSize (Http://www.dianpub.com/download/xml.rar)

2. Picture

Record the start time of the program
$BeginTime =getmicrotime ();
function Grabimage ($url, $filename = "") { 
if ($url = = ""): return false;endif; 
if ($filename = = "") { 
$ext =strrchr ($url, "."); 
if ($ext!= ". gif" && $ext!= ". jpg"): return false;endif; 
$filename =date ("Dmyhis"). $ext; 
} 
Ob_start (); 
ReadFile ($url); 
$img = Ob_get_contents (); 
Ob_end_clean (); 
$size = strlen ($img); 
$FP 2= @fopen ($filename, "a"); 
Fwrite ($fp 2, $img); 
Fclose ($fp 2); 
return $filename; 
} 
$img =grabimage ("Http://www.dianpub.com/images/_1978837_detector_ap100.jpg", ""); 
if ($img): Echo ' <pre></pre> Else:echo "false"; endif;
Record the time when the program is running
$EndTime =getmicrotime ();
Returns the run Time
exit ($EndTime-$BeginTime);

3. Download the full picture

if (!empty ($saveremoteimg)) 
{ 
$body = stripslashes ($body); 
$img _array = Array (); 
Preg_match_all ("/(src| SRC) =[\ "| ' |] {0,} (http:\/\/(. *) \. (gif|jpg|jpeg|bmp|png)) /isu ", $body, $img _array); 
$img _array = Array_unique ($img _array[2]); 
Set_time_limit (0); 
$IMGURL = $img _dir. " /". Strftime ("%y%m%d ", Time ()); 
$imgPath = $base _dir. $imgUrl; 
$milliSecond = strftime ("%h%m%s", Time ()); 
if (!is_dir ($imgPath)) @mkdir ($imgPath, 0777); 
foreach ($img _array as $key => $value) 
{ 
$value = trim ($value); 
$get _file = @file_get_contents ($value); 
$rndFileName = $imgPath. " /". $milliSecond. $key.". substr ($value, -3,3); 
$fileurl = $imgUrl. " /". $milliSecond. $key.". substr ($value, -3,3); 
if ($get _file) 
{ 
$fp = @fopen ($rndFileName, "w"); 
@fwrite ($fp, $get _file); 
@fclose ($FP); 
} 
$body = Ereg_replace ($value, $fileurl, $body); 
$body = Addslashes ($body); 
}

4.PHP Remote File Download class (Support breakpoint continuation)

1). function: Support the download of breakpoint continuation, can calculate transmission rate, can control transmission rate

Easy to use method:

$object = new Httpdownload ();
$object->set_byfile ($file);//server file name, including path
$object->filename = $filename;//download Save as file name
$object-> Download ();

class file:

? 
Class Httpdownload {var $data = null; 
var $data _len = 0; 
var $data _mod = 0; 
var $data _type = 0; var $data _section = 0; 
Section download var $sentSize = 0; 
var $handler = array (' auth ' => null); 
var $use _resume = true; 
var $use _autoexit = false; 
var $use _auth = false; 
var $filename = null; 
var $mime = null; 
var $bufsize = 2048; 
var $seek _start = 0; 
var $seek _end =-1; 
var $totalsizeref = 0; 
var $bandwidth = 0; 
var $speed = 0; 
function Initialize () {global $HTTP _server_vars; if ($this->use_auth)//use authentication {if (! $this->_auth ())//no Authentication {header (' Www-authenticate:b 
ASIC realm= "Please enter your username and password" '); 
Header (' http/1.0 401 Unauthorized '); 
Header (' status:401 unauthorized '); 
if ($this->use_autoexit) exit (); 
return false; } if ($this->mime = null) $this->mime = "Application/octet-stream"; Default MIME if (Isset ($_server[' Http_range ')) | | isset ($HTTP _server_vars[' Http_range '])) {if (isset($HTTP _server_vars[' Http_range ']) 
$seek _range = substr ($HTTP _server_vars[' Http_range '), strlen (' bytes= ')); 
else $seek _range = substr ($_server[' Http_range '), strlen (' bytes= ')); 
$range = Explode ('-', $seek _range); 
if ($range [0] > 0) {$this->seek_start = intval ($range [0]); 
The IF ($range [1] > 0) $this->seek_end = Intval ($range [1]); 
else $this->seek_end =-1; 
if (! $this->use_resume) {$this->seek_start = 0; 
Header ("http/1.0 404 Bad Request"); 
Header ("status:400 bad Request"); 
Exit 
return false; 
else {$this->data_section = 1; 
} else {$this->seek_start = 0; 
$this->seek_end =-1; 
} $this->sentsize=0;
return true; 
The function header ($size, $seek _start=null, $seek _end=null) {header (' Content-type: '. $this->mime); Header (' Content-disposition:attachment filename= "'. $this->filename. 
'"'); 
Header (' last-modified: '. Date (' d, D M Y h:i:s \g\m\t ', $this->data_mod)); if ($this->data_section && $this-&GT;use_resume) {Header ("http/1.0 206 Partial Content"); 
Header ("status:206 Partial Content"); 
Header (' accept-ranges:bytes '); 
Header ("Content-range:bytes $seek _start-$seek _end/$size"); Header ("Content-length:"). 
($seek _end-$seek _start + 1)); 
else {header ("Content-length: $size"); 
} The function download_ex ($size) {if (! $this->initialize ()) return false; 
Ignore_user_abort (TRUE); 
Use Seek End-if ($this->seek_start > ($size-1)) $this->seek_start = 0; 
if ($this->seek_end <= 0) $this->seek_end = $size-1; 
$this->header ($size, $seek, $this->seek_end); 
$this->data_mod = time ();
return true; 
The function download () {if (! $this->initialize ()) return false; 
try {error_log ("Begin download\n", 3, "/usr/local/www/apache22/logs/apache22_php.err"); 
$seek = $this->seek_start; 
$speed = $this->speed; 
$bufsize = $this->bufsize; 
$packet = 1; 
Do some clean up @ob_end_clean (); 
$old _status = Ignore_user_abort (true); @set_timE_limit (0); 
$this->bandwidth = 0; 
$size = $this->data_len; 
if ($this->data_type = = 0)//download from a file {$size = FileSize ($this->data); 
if ($seek > ($size-1)) $seek = 0; 
if ($this->filename = = null) $this->filename = basename ($this->data); 
$res = fopen ($this->data, ' RB '); 
if ($seek) fseek ($res, $seek); 
if ($this->seek_end < $seek) $this->seek_end = $size-1; $this->header ($size, $seek, $this->seek_end); 
Always use $size = $this->seek_end-$seek + 1; while (!) ( connection_aborted () | | 
Connection_status () = = 1) && $size > 0) {if ($size < $bufsize) {echo fread ($res, $size); 
$this->bandwidth + + $size; 
$this->sentsize+= $size; 
else {echo fread ($res, $bufsize); 
$this->bandwidth + + $bufsize; 
$this->sentsize+= $bufsize; 
} $size-= $bufsize; 
Flush (); 
if ($speed > 0 && ($this->bandwidth > $speed * $packet *1024)) {sleep (1); 
$packet + +; 
} fclose ($res); }
ElseIf ($this->data_type = = 1)//download from a string {if ($seek > ($size-1)) $seek = 0; 
if ($this->seek_end < $seek) $this->seek_end = $this->data_len-1; 
$this->data = substr ($this->data, $seek, $this->seek_end-$seek + 1); 
if ($this->filename = = null) $this->filename = time (); 
$size = strlen ($this->data); 
$this->header ($this->data_len, $seek, $this->seek_end); 
while (!connection_aborted () && $size > 0) {if ($size < $bufsize) {$this->bandwidth + = $size; 
$this->sentsize+= $size; 
else {$this->bandwidth + = $bufsize; 
$this->sentsize+= $bufsize; 
Echo substr ($this->data, 0, $bufsize); 
$this->data = substr ($this->data, $bufsize); 
$size-= $bufsize; 
Flush (); 
if ($speed > 0 && ($this->bandwidth > $speed * $packet *1024)) {sleep (1); 
$packet + +; 
} else if ($this->data_type = 2) {//just send a redirect header header (' Location: '. $this->data); 
}if ($this->totalsizeref== $this->sentsize) error_log ("End download\n", 3, "/usr/local/www/apache22/logs/ 
Apache22_php.err "); 
else Error_log ("Download is canceled\n", 3, "/usr/local/www/apache22/logs/apache22_php.err"); 
if ($this->use_autoexit) exit (); 
Restore old status Ignore_user_abort ($old _status); 
Set_time_limit (Ini_get ("Max_execution_time")); 
catch (Exception $e) {error_log ("Cancel download\n". $e, 3, "/usr/local/www/apache22/logs/apache22_php.err");}
return true; 
The function Set_byfile ($dir) {if (is_readable ($dir) && is_file ($dir)) {$this->data_len = 0; 
$this->data = $dir; 
$this->data_type = 0; 
$this->data_mod = Filemtime ($dir); 
$this->totalsizeref = filesize ($dir); 
return true;
else return false; 
The function Set_bydata ($data) {if ($data = = ") return false; 
$this->data = $data; 
$this->data_len = strlen ($data); 
$this->data_type = 1; 
$this->data_mod = time ();
return true; function Set_byurl ($data) {$this->daTa = $data; 
$this->data_len = 0; 
$this->data_type = 2;
return true; 
The function Set_lastmodtime ($time) {$time = Intval ($time); 
if ($time <= 0) $time = time ();
$this->data_mod = $time; 
function _auth () {if (!isset ($_server[' Php_auth_user ')) return false; if (isset ($this->handler[' auth ']) && function_exists ($this->handler[' auth ')) {return $this-> 
handler[' auth ' (' auth ', $_server[' php_auth_user '],$_server[' PHP_AUTH_PW ']); else return true; Must use a handler}}?>

5. PHP uses the GD library to download the remote picture

<?php 
$imgname = "yun_qi_img/4.jpg"; 
$src _im = Imagecreatefromjpeg ($imgname); 
$srcW = Imagesx ($src _im); Get the width 
$srcH = Imagesy ($src _im);//Get the high $dst of the image 
_im = Imagecreatetruecolor ($srcW, $srcH);//Create a new Image object 
Imagecopy ($dst _im, $src _im, 0, 0, 0, 0, $srcW, $srcH); 
Imagejpeg ($dst _im, "newpic.jpg"); Create thumbnail file 
echo "</img>"; 
? >

<?php
header ("Content-type:image/png");
$im = Imagecreatefromjpeg ("yun_qi_img/200602022335325121.jpg");
$white = Imagecolorallocate ($im, 0xf9, 0xd7, 0xCD);
Imagefill ($im, 0, 0, $white);
$text _color = imagecolorallocate ($im, 233,);
Imagestring ($im, 1, 5, 5, "A simple Text String", $text _color);
Imagepng ($im);
Imagedestroy ($im);
? >

Note that this will make PHP allocate memory larger, the application with a large memory server

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.