>  기사  >  php教程  >  PHP实现远程下载文件到本地_php实例

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

PHP中文网
PHP中文网원래의
2016-05-23 17:10:141135검색

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

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

<?php
echo httpcopy("http://www.baidu.com/img/baidu_sylogo1.gif");
 
function httpcopy($url, $file="", $timeout=60) {
  $file = empty($file) ? pathinfo($url,PATHINFO_BASENAME) : $file;
  $dir = pathinfo($file,PATHINFO_DIRNAME);
  !is_dir($dir) && @mkdir($dir,0755,true);
  $url = str_replace(" ","%20",$url);
 
  if(function_exists(&#39;curl_init&#39;)) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $temp = curl_exec($ch);
    if(@file_put_contents($file, $temp) && !curl_error($ch)) {
      return $file;
    } else {
      return false;
    }
  } else {
    $opts = array(
      "http"=>array(
      "method"=>"GET",
      "header"=>"",
      "timeout"=>$timeout)
    );
    $context = stream_context_create($opts);
    if(@copy($url, $file, $context)) {
      //$http_response_header
      return $file;
    } else {
      return false;
    }
  }
}
?>

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

<form method="post">
<input name="url" size="50" />
<input name="submit" type="submit" />
</form>
< ?php
// maximum execution time in seconds
set_time_limit (24 * 60 * 60);
if (!isset($_POST[&#39;submit&#39;])) die();
// folder to save downloaded files to. must end with slash
$destination_folder = &#39;temp/&#39;;
 
$url = $_POST[&#39;url&#39;];
$newfname = $destination_folder . basename($url);
$file = fopen ($url, "rb");
if ($file) {
$newf = fopen ($newfname, "wb");
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
?>

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

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.