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

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

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.


$your_pdf_path = 'https://example.com/Fortrydelsesformular.pdf';

if (!class_exists('WP_Http'))
    include_once( ABSPATH . WPINC . '/class-http.php' );
$http = new WP_Http();
$response = $http->request($your_pdf_path);
if ($response['response']['code'] != 200) {
    return false;
}
$upload = wp_upload_bits(basename($your_pdf_path), null, $response['body']);
if (!empty($upload['error'])) {
    return false;
}
$file_path = $upload['file'];

If you print out the $upload , you will get below

Array
(
    [file] => /var/www/aug15/wp-content/uploads/2019/02/Fortrydelsesformular.pdf
    [url] => https://myadomain.com/Fortrydelsesformular.pdf
    [type] => application/pdf
    [error] => 
)