WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

So this PHP code works for me:

    $ch = curl_init( TCS_CPDF_REMOTE_ZIP );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    $data = curl_exec( $ch );
    curl_close( $ch );
    file_put_contents( TCS_CPDF_LOCAL_ZIP, $data );

but when trying to use the WordPress HTTP API:

    $the_body = wp_remote_retrieve_body( wp_remote_get( TCS_CPDF_REMOTE_ZIP ) );

    file_put_contents( TCS_CPDF_LOCAL_ZIP, $the_body );

I end up getting a 0KB file, so the above WordPress version is not working.

So how do you download a file from a remote location using the WordPress API?

share|improve this question
up vote 6 down vote accepted

Check out download_url() - it's only loaded in the admin, so you'll have to include it (or write your own) if needed on the front-end.

From download_url() you can use:

$response = wp_remote_get( 
        'timeout'  => 300, 
        'stream'   => true, 
        'filename' => TCS_CPDF_LOCAL_ZIP 
share|improve this answer
download_url() always returning this error : WP_Error Object ( [errors:WP_Error:private] => Array ( [http_404] => Array ( [0] => ) ) [error_data:WP_Error:private] => Array ( ) ) what's the problem here? – KeepMove Feb 28 '15 at 16:25
http_404 - i.e. not found. – TheDeadMedic Feb 28 '15 at 16:26
but the url is working when I am trying to open it using browser.. – KeepMove Feb 28 '15 at 16:29
What is the URL? Just because it works for you is not to say they haven't blocked remote agents like WordPress. – TheDeadMedic Feb 28 '15 at 16:30
here is the url http://theme.fm/wp-content/uploads/2011/08/image-sizes-in-wordpress-150x120.png‌​. It is just for testing purpose... – KeepMove Feb 28 '15 at 16:31

If you're in WordPress Admin, you have the function download_url() available (see codex description).

download_url() downloads the file, makes it available in a temp file, and returns the name of a file which you copy/rename and then unlink. See download_url() source here in wp-admin/includes/file.php for more details.

The above answer mentioning download_url() appears to have a wp_remote_get() example - an example for download_url() being:

$permfile = 'safefilename.jpg';
$tmpfile = download_url( $url, $timeout = 300 );
copy( $tmpfile, $permfile );
unlink( $tmpfile ); // must unlink afterwards

Obviously this is very nice. Of course, you'd want to ensure $permfile is sanitized nicely if it is based on an externally supplied filename.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.