A gneric PHP function for fetching remote files
This is a generic PHP function for fetch data remotely. It takes one the remote URL as the only input variable. It returns the saved file name. All data files fetched from remote servers will save to “www-content” folder under web root directory. You can change this name to a folder name you want. The file name is automatically generated based on current date and time to ensure there is no file overwritten.
Source code
function fetch_remote_file($url)
{
$path = parse_url($url);
$fs = @fsockopen($path['host'], 80);
$ext = ereg_replace("^.+\\.([^.]+)$", "\\1", $url);
$filename = date('YmdHis').".".$ext;
if ($fs)
{
// get data
$header = 'GET ' . $url . ' HTTP/1.0' . "\n";
$header .= 'Host: ' . $path['host'] . str_repeat("\n", 2);
fwrite($fs, $header);
$buffer = '';
while ($tmp = fread($fs, 1024)) { $buffer .= $tmp; }
fclose($fs);
// process data
$matches = Array();
preg_match('/Content-Length: ([0-9]+)/', $buffer, $matches);
$data = substr($buffer, -@$matches[1]);
// write file to
$target_path = getcwd() . "/www-content/".$filename;
$Handle = fopen($target_path, 'w');
fwrite($Handle, $data);
fclose($Handle);
return $filename;
}
else
{
return "";
}
}
