copy_dir()
最后更新于:2021-11-25 22:08:23
copy_dir( string$from, string$to, string[]$skip_list=array())Copies a directory from one location to another via the GeChiUI Filesystem Abstraction.
参数
- $from
-
(string) (Required) 源文件 directory.
- $to
-
(string) (Required) Destination directory.
- $skip_list
-
(string[]) (Optional) An array of files/folders to skip copying.
Default value: array()
响应
(true|GC_Error) True on success, GC_Error on failure.
源文件
文件: gc-admin/includes/file.php
function copy_dir( $from, $to, $skip_list = array() ) {
global $gc_filesystem;
$dirlist = $gc_filesystem->dirlist( $from );
if ( false === $dirlist ) {
return new GC_Error( 'dirlist_failed_copy_dir', __( 'Directory listing failed.' ), basename( $to ) );
}
$from = trailingslashit( $from );
$to = trailingslashit( $to );
foreach ( (array) $dirlist as $filename => $fileinfo ) {
if ( in_array( $filename, $skip_list, true ) ) {
continue;
}
if ( 'f' === $fileinfo['type'] ) {
if ( ! $gc_filesystem->copy( $from . $filename, $to . $filename, true, FS_CHMOD_FILE ) ) {
// If copy failed, chmod file to 0644 and try again.
$gc_filesystem->chmod( $to . $filename, FS_CHMOD_FILE );
if ( ! $gc_filesystem->copy( $from . $filename, $to . $filename, true, FS_CHMOD_FILE ) ) {
return new GC_Error( 'copy_failed_copy_dir', __( 'Could not copy file.' ), $to . $filename );
}
}
gc_opcache_invalidate( $to . $filename );
} elseif ( 'd' === $fileinfo['type'] ) {
if ( ! $gc_filesystem->is_dir( $to . $filename ) ) {
if ( ! $gc_filesystem->mkdir( $to . $filename, FS_CHMOD_DIR ) ) {
return new GC_Error( 'mkdir_failed_copy_dir', __( 'Could not create directory.' ), $to . $filename );
}
}
// Generate the $sub_skip_list for the subdirectory as a sub-set of the existing $skip_list.
$sub_skip_list = array();
foreach ( $skip_list as $skip_item ) {
if ( 0 === strpos( $skip_item, $filename . '/' ) ) {
$sub_skip_list[] = preg_replace( '!^' . preg_quote( $filename, '!' ) . '/!i', '', $skip_item );
}
}
$result = copy_dir( $from . $filename, $to . $filename, $sub_skip_list );
if ( is_gc_error( $result ) ) {
return $result;
}
}
}
return true;
}
// Connecting to the filesystem. if ( ! GC_Filesystem() ) { // Unable to connect to the filesystem, FTP credentials may be required or something. // You can request these with request_filesystem_credentials() exit; } // Don't forget that the target directory needs to exist. // If it doesn't already, you'll need to create it. global $gc_filesystem; $gc_filesystem->mkdir( $target_dir ); // Now copy all the files in the source directory to the target directory. copy_dir( $src_dir, $target_dir );