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

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
    
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? –  Ari Susanto Feb 28 at 16:25
    
http_404 - i.e. not found. –  TheDeadMedic Feb 28 at 16:26
    
but the url is working when I am trying to open it using browser.. –  Ari Susanto Feb 28 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 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... –  Ari Susanto Feb 28 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

 
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.