PHP - Downloading a file

This example will show you how to download a file from a remote location.
First we will open a connection to remote host. We will use fopen function to do that. You could also use functions from sockets module if you want more power to control socket behavior. When you open a connection with fopen, you can read and write to that connection just like from/to a file. fopen is good because it is easy to use.


After opening the connection, we read the content of a requested file.
Finally, we are writing the content of a file.

<?php
  $content = "";
  $fp = fopen("http://www.downloadsite.com/file.zip", "rb");
  if (!$fp)
    die("Error opening file.");
  while (!feof($fp))
    $content .= fread($fp, 2048);
  fclose($fp);
  $fp=fopen("file.zip", "w");
  fwrite($fp, $content);
  fclose($fp);
?>

3 Responses to “PHP - Downloading a file”

  1. jeremy Says:

    this php dose not work

  2. Delhi Says:

    Come on, why do you bother if you're not going to give complete instructions? How 'about this for a try:

    // first set your constants once
    ini_set('auto_detect_line_endings', 1); // allows file support for macintosh
    ini_set('default_socket_timeout', 5); // gives some time for a slow internet connection

    // then do this to spider
    $download = file_get_contents($url); // downloads file

  3. neil Says:

    i'm a newbie in PHP,, wat is the code in downloading a file using PHp..

    please help me..

    thanks.

Leave a Reply