Forked from maheshwaghmare/download-file-by-url.php
Created
October 18, 2022 20:17
-
-
Save akshuvo/8ecd450895c275a74bf0de0a7169d765 to your computer and use it in GitHub Desktop.
Download file by URL and move in uploads directory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Download File In Uploads Directory | |
* | |
* Eg. | |
* | |
* $file = download_file( `file-url` ); | |
* | |
* if( $file['success'] ) { | |
* $file_abs_url = $file['data']['file']; | |
* $file_url = $file['data']['file']; | |
* $file_type = $file['data']['type']; | |
* } | |
* | |
* @param string $file Download File URL. | |
* @return array Downloaded file data. | |
*/ | |
if( ! function_exists( 'download_file' ) : | |
function download_file( $file = '' ) { | |
// Gives us access to the download_url() and wp_handle_sideload() functions. | |
require_once( ABSPATH . 'wp-admin/includes/file.php' ); | |
$timeout_seconds = 5; | |
// Download file to temp dir. | |
$temp_file = download_url( $file, $timeout_seconds ); | |
// WP Error. | |
if ( is_wp_error( $temp_file ) ) { | |
return array( | |
'success' => false, | |
'data' => $temp_file->get_error_message(), | |
); | |
} | |
// Array based on $_FILE as seen in PHP file uploads. | |
$file_args = array( | |
'name' => basename( $file ), | |
'tmp_name' => $temp_file, | |
'error' => 0, | |
'size' => filesize( $temp_file ), | |
); | |
$overrides = array( | |
// Tells WordPress to not look for the POST form | |
// fields that would normally be present as | |
// we downloaded the file from a remote server, so there | |
// will be no form fields | |
// Default is true. | |
'test_form' => false, | |
// Setting this to false lets WordPress allow empty files, not recommended. | |
// Default is true. | |
'test_size' => true, | |
// A properly uploaded file will pass this test. There should be no reason to override this one. | |
'test_upload' => true, | |
); | |
// Move the temporary file into the uploads directory. | |
$results = wp_handle_sideload( $file_args, $overrides ); | |
if ( isset( $results['error'] ) ) { | |
return array( | |
'success' => false, | |
'data' => $results, | |
); | |
} | |
// Success! | |
return array( | |
'success' => true, | |
'data' => $results, | |
); | |
} | |
endif; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment