如何在PHP中使用此远程下载文件?

时间:2011-06-03 16:41:26

标签: php function download

我花了很长时间才找到可以使用php从URL下载doc文件的代码......

但我正在试验,无法弄清楚我做错了什么才能让它发挥作用...帮助...... 我只能在http://dev.icalapp.rogersdigitalmedia.com.rogers-test.com

访问我的虚拟主机

我希望暂时从dev.icalapp.rogersdigitalmedia.com.rogers-test.com/Team+Calendar.doc下载文件并将其放回我的网站主机不同的目录,这称为“测试” “ 我尝试了不同的参数,但不知道我做错了什么,请帮助,我很困惑和沮丧我需要做什么...

<?php

/* Function: download remote file */
/* Parameters: $url -> to download | $dir -> where to store file |
    $file_name -> store file as this name - if null, use default*/


function downloadRemoteFile($url,$dir,$file_name = NULL){
    if($file_name == NULL){ $file_name = basename($url);}
    $url_stuff = parse_url($url);
    $port = isset($url_stuff['port']) ? $url_stuff['port'] : 80;

    $fp = fsockopen($url_stuff['host'], $port);
    if(!$fp){ return false;}

    $query  = 'GET ' . $url_stuff['path'] . " HTTP/1.0\n";
    $query .= 'Host: ' . $url_stuff['host'];
    $query .= "\n\n";

    fwrite($fp, $query);

    while ($tmp = fread($fp, 8192))   {
        $buffer .= $tmp;
    }

    preg_match('/Content-Length: ([0-9]+)/', $buffer, $parts);
    $file_binary = substr($buffer, - $parts[1]);
    if($file_name == NULL){
        $temp = explode(".",$url);
        $file_name = $temp[count($temp)-1];
    }
    $file_open = fopen($dir . "/" . $file_name,'w');
    if(!$file_open){ return false;}
    fwrite($file_open,$file_binary);
    fclose($file_open);
    return true;
} 
?> 

2 个答案:

答案 0 :(得分:2)

这是函数所需的所有代码:

$url = "http://dev.icalapp.rogersdigitalmedia.com.rogers-test.com/Team+Calendar.doc";
$dir = "testing";
downloadRemoteFile($url,$dir);

目标目录($dir)也应该是可写的。您的网络服务器必须允许出站HTTP连接。

答案 1 :(得分:0)

你需要在你的php.ini中允许你允许url fopen联系你的webhost,之后就可以了吗

$fp = fopen( $url );
$data = fread( $fp, 204800) // 2 mb

使用应该执行此操作的fwrite将$ data写入目标文件

另外,你也可以使用

file_get_contents and file_put_contents