首页 > 开发 > PHP > 正文

PHP实现远程下载文件到本地

2024-05-04 23:35:19
字体:大 中 小
来源:转载
供稿:网友

经常写采集器发布接口需要使用到远程附件的功能,所以自己写了一个PHP远程下载文件到本地的函数,一般情况下已经够用了,如果服务器支持CURL函数,程序则会优先选择CURL,有需要的小伙伴可以参考下。

代码很简单就不多废话了,直接奉上:

 

 
  1. <?php 
  2. echo httpcopy("http://www.baidu.com/img/baidu_sylogo1.gif"); 
  3.  
  4. function httpcopy($url, $file="", $timeout=60) { 
  5. $file = emptyempty($file) ? pathinfo($url,PATHINFO_BASENAME) : $file; 
  6. $dir = pathinfo($file,PATHINFO_DIRNAME); 
  7. !is_dir($dir) && @mkdir($dir,0755,true); 
  8. $url = str_replace(" ","%20",$url); 
  9.  
  10. if(function_exists('curl_init')) { 
  11. $ch = curl_init(); 
  12. curl_setopt($ch, CURLOPT_URL, $url); 
  13. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); 
  14. curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
  15. $temp = curl_exec($ch); 
  16. if(@file_put_contents($file, $temp) && !curl_error($ch)) { 
  17. return $file; 
  18. } else { 
  19. return false; 
  20. } 
  21. } else { 
  22. $opts = array( 
  23. "http"=>array( 
  24. "method"=>"GET", 
  25. "header"=>"", 
  26. "timeout"=>$timeout) 
  27. ); 
  28. $context = stream_context_create($opts); 
  29. if(@copy($url, $file, $context)) { 
  30. //$http_response_header 
  31. return $file; 
  32. } else { 
  33. return false; 
  34. } 
  35. } 
  36. } 
  37. ?> 

再来个远程下载文件到服务器

 

 
  1. <form method="post"> 
  2. <input name="url" size="50" /> 
  3. <input name="submit" type="submit" /> 
  4. </form> 
  5. < ?php 
  6. // maximum execution time in seconds 
  7. set_time_limit (24 * 60 * 60); 
  8. if (!isset($_POST['submit'])) die(); 
  9. // folder to save downloaded files to. must end with slash 
  10. $destination_folder = 'temp/'; 
  11.  
  12. $url = $_POST['url']; 
  13. $newfname = $destination_folder . basename($url); 
  14. $file = fopen ($url, "rb"); 
  15. if ($file) { 
  16. $newf = fopen ($newfname, "wb"); 
  17. if ($newf) 
  18. while(!feof($file)) { 
  19. fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 ); 
  20. } 
  21. } 
  22. if ($file) { 
  23. fclose($file); 
  24. } 
  25. if ($newf) { 
  26. fclose($newf); 
  27. } 
  28. ?> 

以上所述就是本文的全部内容了,希望大家能够喜欢。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表