Showing posts with label Remote Server using PHP. Show all posts
Showing posts with label Remote Server using PHP. Show all posts

Sunday, January 16, 2011

Download an Image file from Remote Server using PHP

To get remote file:

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;
}



function call:

$tmp_filename = "tmp_".$filename_noext.$_POST['ext'];
downloadRemoteFile($filename, $tmp_path, $tmp_filename);

Popular Posts