How to use WordPress HTTP API to download file from remote location

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?

3 s
3

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 
    ) 
);

Leave a Comment