Hey guys. I need to download a file to my server given a URL but it isn't working. For some reason it isn't downloading the whole file, it is only getting part. Here is my code:
<?php
/* Tutorial by AwesomePHP.com -> www.AwesomePHP.com */
/* 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;
}
?>
I found it from Here
Like I said, I am only getting about 4 Kb of the files I am testing with:
Test Link 1
Test Link 2
Test Link 3
Test Link 4
Test Link 5
Thanks in advance!