Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
add comment

2 Answers 2

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( 
    TCS_CPDF_REMOTE_ZIP, 
    array( 
        'timeout'  => 300, 
        'stream'   => true, 
        'filename' => TCS_CPDF_LOCAL_ZIP 
    ) 
);
share|improve this answer
add comment

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
add comment

Your Answer

 
discard

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.