热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

php下载远程图片的几种方法

php下载远程图片的几种方法获取远程文件大小及信息的函数记录程序开始的时间
1.获取远程文件大小及信息的函数

function getFileSize($url){ 
         $url = parse_url($url); 
         if($fp = @fsockopen($url[’host’],empty($url[’port’])?80:$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.图片

//记录程序开始的时间
$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); 
$fp2=@fopen($filename, "a"); 
fwrite($fp2,$img); 
fclose($fp2); 
return $filename; 
} 

$img=GrabImage("http://www.dianpub.com/images/_1978837_detector_ap100.jpg",""); 
if($img):echo '
';else:echo "false";endif; //记录程序运行结束的时间 $EndTime=getmicrotime(); //返回运行时间 exit($EndTime-$BeginTime); 3.全文下载图片 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远程文件下载类(支持断点续传) 1).功能:支持断点续传的下载,能计算传输率,能控制传输率 简易使用方法: $object = new httpdownload(); $object->set_byfile($file);//服务器文件名,包括路径 $object->filename = $filename;//下载另存为的文件名 $object->download(); 类文件: 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 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]); } 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; } 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/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 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->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; } 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; } 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; } 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 使用GD库下载远程图片 "; ?>

 


推荐阅读
  • 本文详细介绍了SQL日志收缩的方法,包括截断日志和删除不需要的旧日志记录。通过备份日志和使用DBCC SHRINKFILE命令可以实现日志的收缩。同时,还介绍了截断日志的原理和注意事项,包括不能截断事务日志的活动部分和MinLSN的确定方法。通过本文的方法,可以有效减小逻辑日志的大小,提高数据库的性能。 ... [详细]
  • 本文介绍了Python高级网络编程及TCP/IP协议簇的OSI七层模型。首先简单介绍了七层模型的各层及其封装解封装过程。然后讨论了程序开发中涉及到的网络通信内容,主要包括TCP协议、UDP协议和IPV4协议。最后还介绍了socket编程、聊天socket实现、远程执行命令、上传文件、socketserver及其源码分析等相关内容。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的详细步骤
    本文详细介绍了搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的步骤,包括环境说明、相关软件下载的地址以及所需的插件下载地址。 ... [详细]
  • 本文介绍了使用AJAX的POST请求实现数据修改功能的方法。通过ajax-post技术,可以实现在输入某个id后,通过ajax技术调用post.jsp修改具有该id记录的姓名的值。文章还提到了AJAX的概念和作用,以及使用async参数和open()方法的注意事项。同时强调了不推荐使用async=false的情况,并解释了JavaScript等待服务器响应的机制。 ... [详细]
  • PHP设置MySQL字符集的方法及使用mysqli_set_charset函数
    本文介绍了PHP设置MySQL字符集的方法,详细介绍了使用mysqli_set_charset函数来规定与数据库服务器进行数据传送时要使用的字符集。通过示例代码演示了如何设置默认客户端字符集。 ... [详细]
  • Java序列化对象传给PHP的方法及原理解析
    本文介绍了Java序列化对象传给PHP的方法及原理,包括Java对象传递的方式、序列化的方式、PHP中的序列化用法介绍、Java是否能反序列化PHP的数据、Java序列化的原理以及解决Java序列化中的问题。同时还解释了序列化的概念和作用,以及代码执行序列化所需要的权限。最后指出,序列化会将对象实例的所有字段都进行序列化,使得数据能够被表示为实例的序列化数据,但只有能够解释该格式的代码才能够确定数据的内容。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文介绍了如何使用php限制数据库插入的条数并显示每次插入数据库之间的数据数目,以及避免重复提交的方法。同时还介绍了如何限制某一个数据库用户的并发连接数,以及设置数据库的连接数和连接超时时间的方法。最后提供了一些关于浏览器在线用户数和数据库连接数量比例的参考值。 ... [详细]
  • 如何使用Java获取服务器硬件信息和磁盘负载率
    本文介绍了使用Java编程语言获取服务器硬件信息和磁盘负载率的方法。首先在远程服务器上搭建一个支持服务端语言的HTTP服务,并获取服务器的磁盘信息,并将结果输出。然后在本地使用JS编写一个AJAX脚本,远程请求服务端的程序,得到结果并展示给用户。其中还介绍了如何提取硬盘序列号的方法。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 本文介绍了使用PHP实现断点续传乱序合并文件的方法和源码。由于网络原因,文件需要分割成多个部分发送,因此无法按顺序接收。文章中提供了merge2.php的源码,通过使用shuffle函数打乱文件读取顺序,实现了乱序合并文件的功能。同时,还介绍了filesize、glob、unlink、fopen等相关函数的使用。阅读本文可以了解如何使用PHP实现断点续传乱序合并文件的具体步骤。 ... [详细]
  • 本文介绍了RPC框架Thrift的安装环境变量配置与第一个实例,讲解了RPC的概念以及如何解决跨语言、c++客户端、web服务端、远程调用等需求。Thrift开发方便上手快,性能和稳定性也不错,适合初学者学习和使用。 ... [详细]
  • 关于我们EMQ是一家全球领先的开源物联网基础设施软件供应商,服务新产业周期的IoT&5G、边缘计算与云计算市场,交付全球领先的开源物联网消息服务器和流处理数据 ... [详细]
author-avatar
孤独的李新_780
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有