PHP Download remote pictures and save to local method summary, _php tutorial

Source: Internet
Author: User
Tags fread php download

PHP download remote picture and save to local method summary,


1. functions to obtain remote file size and information

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

The time at which the logger starts $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 '
'; Else:echo "false"; endif;//Log program run time $endtime=getmicrotime ();//Return Run time exit ($EndTime-$BeginTime);

3. Full-Text Download 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 = $i Mgpath. " /". $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 (supports breakpoint continuation)

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

Easy to use method:

$object = new Httpdownload (); $object->set_byfile ($file);//server file name, including path $object->filename = $filename;// Download Save as filename $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:basic realm= ' Please enter your username and password "'); header (' http/1.0 4 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]),} if ($range [1] > 0) $this->seek_end = Intval ($ran GE[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 Req Uest "); Exit return false; } else {$this->data_section = 1;}} else {$this->seek_start = 0; $this->seek_end =-1;} $this->sentsize=0; return true;} 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->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");}} function Download_ex ($size) {if (! $this->initialize ()) return false; Ignore_user_abort (true);//use seek end here 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;} function Download () {if (! $this->initialize ()) return false; try {error_log ("Begin download\n", 3, "/usr/local/www/ap Ache22/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 the last seek $size = $this->seek_end-$seek + 1; while (!) ( connection_aborted () | | Connection_status () = = 1) && $size > 0) {if ($size < $bufsize) {echo fread ($res, $size); $this->bandwi DTH + = $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_e nd< $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-&gt ; 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-&gt ; 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;} function Set_byfile ($dir) {if (is_readable ($dir) && is_file ($dir)) {$this->data_len = 0; $this->data = $di R $this->data_type = 0; $this->data_mod = Filemtime ($dir); $this->totalsizeref = filesize ($dir); return true; } else return false;} function Set_bydata ($data) {if ($data = =) return false; $this->data = $data; $this->data_len = strlen ($data); $t His->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;} 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; You must use a handler}}?>

5. PHP download remote image using GD library

<?php $imgname = "Http://imgdujia.kuxun.cn/newpic/929/812929/4.jpg"; $src _im = Imagecreatefromjpeg ($imgname); $srcW = Imagesx ($src _im); Obtain the width of the image $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 a thumbnail file echo "";? ><?phpheader ("Content-type:image/png"); $im = Imagecreatefromjpeg ("http://postimg.mop.com/ 200602/02/74/122374/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); Magepng ($im); Imagedestroy ($im);? >

Note that this is going to make the PHP allocation memory larger, the application with a large memory server

Articles you may be interested in:

    • PHP with password feature and download remote file save locally specified directory modify the enhanced version
    • Download remote pictures to local implementation code using Thinkphp's own HTTP class
    • function code for downloading remote images from content in PHP with regular expressions
    • parsing php Download remote picture function can forge the route
    • PHP implementation of download remote image Custom Function sharing
    • Using GD Library in PHP for remote picture Download instance
    • PHP matches the remote image address in the article and downloads the image to a local

http://www.bkjia.com/PHPjc/1094756.html www.bkjia.com true http://www.bkjia.com/PHPjc/1094756.html techarticle php Download remote picture and save to local method summary, 1. function GetFileSize ($url) {$url = Parse_url ($url) for remote file size and information, if ($fp = @fsockopen ($url [ ' H ...

  • 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.