我正在尝试将文件从一个位置下载到另一个位置。该代码工作正常。以下是代码片段:
Helper Function - 在中创建目录/uploads/{$dir_name}/
和返回路径。
/**
* Create folder in /uploads/{$dir_name}/
* @return array()
*/
function get_dirpath( $dir_name = \'test\' ) {
$wp_info = wp_upload_dir();
// SSL workaround.
if ( is_ssl() ) {
$wp_info[\'baseurl\'] = str_ireplace( \'http://\', \'https://\', $wp_info[\'baseurl\'] );
}
// Build the paths.
$dir_info = array(
\'path\' => $wp_info[\'basedir\'] . \'/\' . $dir_name . \'/\',
\'url\' => $wp_info[\'baseurl\'] . \'/\' . $dir_name . \'/\'
);
// Create the upload dir if it doesn\'t exist.
if ( ! file_exists( $dir_info[\'path\'] ) ) {
// Create the directory.
mkdir( $dir_info[\'path\'] );
// Add an index file for security.
file_put_contents( $dir_info[\'path\'] . \'index.html\', \'\' );
}
return $dir_info;
}
Way - 1 - 使用PHP
copy()
函数-
{完美工作}。
$dir_info = get_dirpath( \'test\' );
$remote_file = \'https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png\';
$local_file = trailingslashit( $dir_info[\'path\'] ) . basename( $remote_file );
if ( copy( $remote_file, $local_file ) ) {
// Successfully copy file from URL
}
Way - 2 - 使用WordPress
WP_Filesystem_Direct
-
{完美工作}require_once ABSPATH . \'/wp-admin/includes/class-wp-filesystem-base.php\';
require_once ABSPATH . \'/wp-admin/includes/class-wp-filesystem-direct.php\';
$my_filesystem = new WP_Filesystem_Direct( array() );
if ( $my_filesystem->copy( $remote_file, $local_file, true) ) {
// Successfully copy file from URL
}
两者都很完美。
此代码段:
创建文件googlelogo_color_272x92dp.png
目录中的li>
/wp-content/uploads/test/
来源https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png
我想,我需要Way - 2
. 但是,这样做对吗include files
并创建new WP_Filesystem_Direct()
对象我搜索了一下,发现Copy a file from a plugin into my theme directory和How to use copy() function and paste file in /wp-content/themes directory
但是,未找到任何使用Way - 2
.
Edited: - 这个global $wp_filesystem
做同样的事情way - 2
. 但是,它不起作用(不知道为什么!)。
此外,如果文件下载失败,如何获取有效的错误消息?