download_url() │ WP 2.5.0 Завантажує файл (УРЛ) у тимчасовий каталог PHP. Працює на основі WordPress HTTP API.
Майте на увазі, при виклику функції завжди потрібно видаляти файл через unlink()
У фронт-енді для роботи функції потрібні такі файли:
require_once ABSPATH. 'wp-admin/includes/file.php'; Повертає Строку|WP_Error
. Назва файлу (абсолютний шлях до файлу на сервері), якщо файл успішно завантажено. WP_Error об’єкт у разі помилки.
Використання download_url($url, $timeout);
$url
(рядок) (обов’язковий)
УРЛ файлу, який потрібно завантажити до тимчасової директорії.
$timeout
(число)
Час, після якого функція перестане завантажувати файл.
Типово: 300
$signature_verification
(true/false) (WP 5.2) Чи потрібно перевіряти сигнатуру файлу, що завантажується.
true означає, що потрібно перевіряти сигнатуру, тільки якщо файл завантажується з хостів wordpress.org , downloads.wordpress.org , sworg . Розширити список хостів можна через хук verify_file_signature() . Типово: false
Приклади #1 Приклад завантаження файлу до тимчасового каталогу PHP У цьому прикладі завантажимо логотип WordPress та перевіримо завантаження на помилки. Також після обробки видалимо тимчасовий файл на сервері.
// If the function it's no available, require it.
require_once ABSPATH. 'wp-admin/includes/file.php';
$sourse_url = 'https://sworg/style/images/wp-header-logo.png';
$dest_path = wp_upload_dir()['basedir'] . '/wp-header-logo.png'; //wp-content/uploads/myfile.ext
$ tmp_file = download_url ($ sourse_url);
if( is_wp_error( $tmp_file ) ){
echo $tmp_file->get_error_message();
}
else {
// Зображення файлу до кінцевого списку і deletes temporary file.
copy($tmp_file, $dest_path);
echo "Copied to: $dest_path";
}
// delete the temporary file
@ unlink ($ tmp_file); Додати свій приклад
список змінЗ версії 2.5.0 Введено. З версії 5.2.0 Signature Verification with SoftFail був added. З версії 5.9.0 Support for Content-Disposition filename був added.
Код download_url() download url WP 6.0.2 function download_url( $url, $timeout = 300, $signature_verification = false ) {
// WARNING: File не є автоматично deleted, script must unlink() file.
if ( ! $url ) {
return new WP_Error( 'http_no_url', __( 'Invalid URL Provided.' ) );
}
$url_path = parse_url($url, PHP_URL_PATH);
$url_filename = '';
if ( is_string( $url_path ) && '' !== $url_path ) {
$url_filename = basename( $url_path );
}
$tmpfname = wp_tempnam( $url_filename );
if (! $tmpfname) {
return new WP_Error( 'http_no_file', __( 'Could not create temporary file.' ) );
}
$response = wp_safe_remote_get(
$url,
array(
'timeout' => $timeout,
'stream' => true,
'filename' => $tmpfname,
)
);
if ( is_wp_error( $response ) ) {
unlink($tmpfname);
return $response;
}
$response_code = wp_remote_retrieve_response_code($response);
if ( 200 !== $response_code ) {
$ data = array (
'code' => $response_code,
);
/ / Retrieve a sample of the response body for debugging purposes.
$ tmpf = fopen ($ tmpfname, 'rb');
if ( $tmpf ) {
/**
* Filters the maximum error response body size в `download_url()`.
*
* @ Since 5.1.0
*
* @see download_url()
*
* @param int $size Найвища помилка response body size. Default 1 KB.
*/
$response_size = apply_filters( 'download_url_error_max_body_size', KB_IN_BYTES );
$ data [ 'body'] = fread ($ tmpf, $ response_size);
fclose($tmpf);
}
unlink($tmpfname);
return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ), $data );
}
$content_disposition = wp_remote_retrieve_header( $response, 'content-disposition' );
if ($content_disposition) {
$content_disposition = strtolower( $content_disposition );
if ( 0 === strpos( $content_disposition, 'attachment; filename=' ) ) {
$tmpfname_disposition = sanitize_file_name( substr( $content_disposition, 21 ) );
} else {
$tmpfname_disposition = '';
}
// Potential file name must be valid string.
if ( $tmpfname_disposition && is_string( $tmpfname_disposition )
&& ( 0 === validate_file( $tmpfname_disposition ) )
) {
$tmpfname_disposition = dirname($tmpfname). '/'. $tmpfname_disposition;
if ( rename( $tmpfname, $tmpfname_disposition ) ) {
$tmpfname = $tmpfname_disposition;
}
if ( ( $tmpfname !== $tmpfname_disposition ) && file_exists( $tmpfname_disposition ) ) {
unlink( $tmpfname_disposition );
}
}
}
$content_md5 = wp_remote_retrieve_header( $response, 'content-md5');
if ( $content_md5 ) {
$md5_check = verify_file_md5( $tmpfname, $content_md5 );
if ( is_wp_error( $md5_check ) ) {
unlink($tmpfname);
return $md5_check;
}
}
// Якщо ви знайдете певні заяви про підтвердження, check to see if this URL supports it.
if ($signature_verification) {
/**
* Filters List of hosts which should have Signature Verification attempted on.
*
* @ Since 5.2.0
*
* @param string[] $hostnames List of hostnames.
*/
$signed_hostnames = apply_filters( 'wp_signature_hosts', array( 'wordpress.org', 'downloads.wordpress.org', 'sworg' ) );
$signature_verification = in_array( parse_url( $url, PHP_URL_HOST ), $signed_hostnames, true );
}
// Perform signature valiation if supported.
if ($signature_verification) {
$signature = wp_remote_retrieve_header( $response, 'x-content-signature');
if ( ! $signature ) {
// Retrieve signatures from a file if the header wasn't included.
// WordPress.org stores signatures at $package_url.sig.
$signature_url = false;
if ( is_string( $url_path ) && ( '.zip' === substr( $url_path, -4 ) || '.tar.gz' === substr( $url_path, -7 ) ) ) {
$signature_url = str_replace( $url_path, $url_path . '.sig', $url );
}
/**
* Filters the URL where the signature for a file is located.
*
* @ Since 5.2.0
*
* @param false|string $signature_url URL-адреси, які можуть бути знайдені для файлу, або false, якщо немає відомості.
* @param string $url URL-адреса буде визначена.
*/
$signature_url = apply_filters( 'wp_signature_url', $signature_url, $url );
if ($signature_url) {
$signature_request = wp_safe_remote_get(
$signature_url,
array(
'limit_response_size' => 10 * KB_IN_BYTES, // 10KB повинна бути великою згодою для того, щоб дати певні signatures.
)
);
if ( ! is_wp_error( $signature_request ) && 200 === wp_remote_retrieve_response_code( $signature_request ) ) {
$signature = explode( "n", wp_remote_retrieve_body( $signature_request ) );
}
}
}
// Perform the checks.
$signature_verification = verify_file_signature( $tmpfname, $signature, $url_filename );
}
if ( is_wp_error( $signature_verification ) ) {
if (
/**
* Filters whether Signature Verification failures повинні бути дозволені до soft fail.
*
* WARNING: Це може бути відремонтовано від майбутнього виконання.
*
* @ Since 5.2.0
*
* @param bool $signature_softfail Якщо softfail is allowed.
* @param string $url url being accessed.
*/
apply_filters( 'wp_signature_softfail', true, $url )
) {
$signature_verification->add_data( $tmpfname, 'softfail-filename' );
} else {
/ / Hard-fail.
unlink($tmpfname);
}
return $signature_verification;
}
return $tmpfname;
} Зв’язані функції