It took me FOREVER to finally find code that can download a doc file using php from a URL...
But I am experimenting and can't figure out what I am doing wrong to make it work...help.. My webhost only I can access is at http://dev.icalapp.rogersdigitalmedia.com.rogers-test.com
I would like it for the time being to download a file from dev.icalapp.rogersdigitalmedia.com.rogers-test.com/Team+Calendar.doc and put it back into my web hosts different directory which is called "testing" I tried different parameters but dont know what I am doing wrong please help, I am so confused and frustrated what do I need to do here...
<?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]+)/', $buff开发者_开发知识库er, $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;
}
?>
This is all the code you need with the function:
$url = "http://dev.icalapp.rogersdigitalmedia.com.rogers-test.com/Team+Calendar.doc";
$dir = "testing";
downloadRemoteFile($url,$dir);
Also the target directory ($dir
) should be writeable. And your webserver must allow outbound HTTP connections.
you will need to have allow url fopen allowed in your php.ini contact your webhost for this after that you can do
$fp = fopen( $url );
$data = fread( $fp, 204800) // 2 mb
and write $data to a destination file using fwrite that should do it
other wise you can also use
file_get_contents and file_put_contents
精彩评论