Tuesday, 15 January 2013

How to download a file to your own server (from a remote source) ?

Download file (without proxy)

The following php script helps you to download a file from a remote url ($url) to your local server directory($dir) :-



function download($url,$at)
{
$remote_url = "$url";
$local_filename = $at; // say :- "C:/123.jpg"
try
  {
  $file = fopen ($remote_url, "rb");
  if (! $file) {
        throw new Exception("Could not open the file!");
 }
  if ($file) {
    $newf = fopen ($local_filename, "wb");

    if ($local_filename)
    while(!feof($file)) {
      fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
    }
  }

  if ($file) {
    fclose($file);
  }

  if ($newf) {
    fclose($newf);
  }
  }
  catch(Exception $e)
  {
  echo "Error (File: ".$e->getFile().", line ".
          $e->getLine()."): ".$e->getMessage();
  }
}

------------------------------------------------------------------------------------------------------------

Download File (With Proxy)



This method does not work if you use a proxy . For that we need to use a modified method , which will be something like this :-



function modified_download($url,$at)
{

$opts = array(
  'http'=>array(
    'method'=>"GET",
    'proxy'=>"YOUR_PROXY:PORT",
'header'=>'Content-type : image/JPEG',
'request_fulluri' => True // do not miss out this line
  )
);

$context = stream_context_create($opts);

/* Sends an http request to www.example.com
   with additional headers shown above */



$target = $url;
$local_filename = $at;
try
  {
  $file = fopen($target,"rb",false,$context);
  if (! $file) {
        throw new Exception("Could not open the file!");
    }
  if ($file) {
    $nf = fopen ($local_filename, "wb");

    if ($nf)
    while(!feof($file)) {
      fwrite($nf, fread($file, 1024 * 8 ), 1024 * 8 );
    }
  }

  if ($file) {
    fclose($file);
  }

  if ($nf) {
    fclose($newf);
  }
  }
  catch(Exception $e)
  {
  echo "Error (File: ".$e->getFile().", line ".
          $e->getLine()."): ".$e->getMessage();
  }

}


1 comment: