NKS
NKS

Reputation: 1160

Downloading large files using PHP

I am using following code to download files from some remote server using php

//some php page parsing code
$url  = 'http://www.domain.com/'.$fn;
$path = 'myfolder/'.$fn;
$fp = fopen($path, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
// some more code

but instead of downloading and saving the file in the directory it is showing the file contents (junk characters as file is zip) directly on the browser only.

I guess it might be an issue with header content, but not know exactly ...

Thanks

Upvotes: 0

Views: 652

Answers (3)

John K
John K

Reputation: 905

Use the following function that includes error handling.

// Download and save a file with curl
function curl_dl_file($url, $dest, $opts = array())
{
    // Open the local file to save. Suppress warning
    // upon failure.
    $fp = @fopen($dest, 'w+');

    if (!$fp)
    {
        $err_arr = error_get_last();
        $error = $err_arr['message'];
        return $error;
    }

    // Set up curl for the download
    $ch = curl_init($url);

    if (!$ch)
    {
        $error = curl_error($ch);
        fclose($fp);
        return $error;
    }

    $opts[CURLOPT_FILE] = $fp;

    // Set up curl options
    $failed = !curl_setopt_array($ch, $opts);

    if ($failed)
    {
        $error = curl_error($ch);
        curl_close($ch);
        fclose($fp);
        return $error;
    }

    // Download the file
    $failed = !curl_exec($ch);

    if ($failed)
    {
        $error = curl_error($ch);
        curl_close($ch);
        fclose($fp);
        return $error;
    }

    // Close the curl handle.
    curl_close($ch);

    // Flush buffered data to the file
    $failed = !fflush($fp);

    if ($failed)
    {
        $err_arr = error_get_last();
        $error = $err_arr['message'];
        fclose($fp);
        return $error;
    }

    // The file has been written successfully at this point. 
    // Close the file pointer
    $failed = !fclose($fp);

    if (!$fp)
    {
        $err_arr = error_get_last();
        $error = $err_arr['message'];
        return $error;
    }
}

Upvotes: 1

Nav
Nav

Reputation: 86

As mentioned in http://php.net/manual/en/function.curl-setopt.php :

CURLOPT_RETURNTRANSFER: TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.

So you can simply add this line before your curl_exec line:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

and you will have the content in $data variable.

Upvotes: 1

thatthatisis
thatthatisis

Reputation: 783

I believe you need:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

to make curl_exec() return the data, and:

$data = curl_exec($ch);
fwrite($fp, $data);

to get the file actually written.

Upvotes: 1

Related Questions