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

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

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

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

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

  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. $url = $_POST['url'];
  12. $newfname = $destination_folder . basename($url);
  13. $file = fopen ($url, "rb");
  14. if ($file) {
  15. $newf = fopen ($newfname, "wb");
  16. if ($newf)
  17. while(!feof($file)) {
  18. fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
  19. }
  20. }
  21. if ($file) {
  22. fclose($file);
  23. }
  24. if ($newf) {
  25. fclose($newf);
  26. }
  27. ?>