PHP를 사용하여 디렉토리의 전체 내용을 다른 디렉토리로 복사
디렉토리의 전체 내용을 다른 위치로 복사하려고했습니다.
copy ("old_location/*.*","new_location/");
그러나 스트림을 찾을 수 없다고 말하면 true를 찾을 수 없습니다 *.*
.
다른 방법
고마워 데이브
복사본 은 단일 파일 만 처리 하는 것 같습니다 . 다음은 복사 설명서 페이지 의이 메모 에서 찾은 재귀 적으로 복사하는 기능입니다 .
<?php
function recurse_copy($src,$dst) {
$dir = opendir($src);
@mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
?>
로 여기에 설명 된 ,이 심볼릭 링크 처리를 너무 걸리는 또 다른 방법은 다음과 같습니다
/**
* Copy a file, or recursively copy a folder and its contents
* @author Aidan Lister <aidan@php.net>
* @version 1.0.1
* @link http://aidanlister.com/2004/04/recursively-copying-directories-in-php/
* @param string $source Source path
* @param string $dest Destination path
* @param int $permissions New folder creation permissions
* @return bool Returns true on success, false on failure
*/
function xcopy($source, $dest, $permissions = 0755)
{
// Check for symlinks
if (is_link($source)) {
return symlink(readlink($source), $dest);
}
// Simple copy for a file
if (is_file($source)) {
return copy($source, $dest);
}
// Make destination directory
if (!is_dir($dest)) {
mkdir($dest, $permissions);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Deep copy directories
xcopy("$source/$entry", "$dest/$entry", $permissions);
}
// Clean up
$dir->close();
return true;
}
copy ()는 파일에서만 작동합니다.
DOS 카피와 유닉스 cp 명령어는 재귀 적으로 카피 될 것이므로, 가장 빠른 해결책은 이것들을 사용하는 것입니다. 예 :
`cp -r $src $dest`;
그렇지 않으면 opendir
/ 를 사용 readdir
하거나 scandir
디렉토리의 내용을 읽고 결과를 반복해야하며, is_dir이 각각에 대해 true를 리턴하면 해당 디렉토리로 돌아가십시오.
예 :
function xcopy($src, $dest) {
foreach (scandir($src) as $file) {
if (!is_readable($src . '/' . $file)) continue;
if (is_dir($src .'/' . $file) && ($file != '.') && ($file != '..') ) {
mkdir($dest . '/' . $file);
xcopy($src . '/' . $file, $dest . '/' . $file);
} else {
copy($src . '/' . $file, $dest . '/' . $file);
}
}
}
가장 좋은 해결책은!
<?php
$src = "/home/www/domain-name.com/source/folders/123456";
$dest = "/home/www/domain-name.com/test/123456";
shell_exec("cp -r $src $dest");
echo "<H3>Copy Paste completed!</H3>"; //output when done
?>
function full_copy( $source, $target ) {
if ( is_dir( $source ) ) {
@mkdir( $target );
$d = dir( $source );
while ( FALSE !== ( $entry = $d->read() ) ) {
if ( $entry == '.' || $entry == '..' ) {
continue;
}
$Entry = $source . '/' . $entry;
if ( is_dir( $Entry ) ) {
full_copy( $Entry, $target . '/' . $entry );
continue;
}
copy( $Entry, $target . '/' . $entry );
}
$d->close();
}else {
copy( $source, $target );
}
}
다른 곳에서 말했듯 copy
이 패턴이 아닌 소스의 단일 파일로만 작동합니다. 패턴별로 복사 glob
하려면 파일을 판별하고 복사를 실행하십시오. 하위 디렉토리는 복사하지 않으며 대상 디렉토리를 작성하지도 않습니다.
function copyToDir($pattern, $dir)
{
foreach (glob($pattern) as $file) {
if(!is_dir($file) && is_readable($file)) {
$dest = realpath($dir . DIRECTORY_SEPARATOR) . basename($file);
copy($file, $dest);
}
}
}
copyToDir('./test/foo/*.txt', './test/bar'); // copies all txt files
<?php
function copy_directory( $source, $destination ) {
if ( is_dir( $source ) ) {
@mkdir( $destination );
$directory = dir( $source );
while ( FALSE !== ( $readdirectory = $directory->read() ) ) {
if ( $readdirectory == '.' || $readdirectory == '..' ) {
continue;
}
$PathDir = $source . '/' . $readdirectory;
if ( is_dir( $PathDir ) ) {
copy_directory( $PathDir, $destination . '/' . $readdirectory );
continue;
}
copy( $PathDir, $destination . '/' . $readdirectory );
}
$directory->close();
}else {
copy( $source, $destination );
}
}
?>
마지막 4 번째 줄부터
$source = 'wordpress';//i.e. your source path
과
$destination ='b';
필자의 코드에 감사하게 사용 된 탁월한 답변에 대해 Felix Kling에게 전적으로 감사해야합니다. 성공 또는 실패를보고하기 위해 부울 리턴 값을 약간 개선했습니다.
function recurse_copy($src, $dst) {
$dir = opendir($src);
$result = ($dir === false ? false : true);
if ($result !== false) {
$result = @mkdir($dst);
if ($result === true) {
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' ) && $result) {
if ( is_dir($src . '/' . $file) ) {
$result = recurse_copy($src . '/' . $file,$dst . '/' . $file);
} else {
$result = copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
}
return $result;
}
@Kzoty 답변의 정리 된 버전. Kzoty 감사합니다.
용법
Helper::copy($sourcePath, $targetPath);
class Helper {
static function copy($source, $target) {
if (!is_dir($source)) {//it is a file, do a normal copy
copy($source, $target);
return;
}
//it is a folder, copy its files & sub-folders
@mkdir($target);
$d = dir($source);
$navFolders = array('.', '..');
while (false !== ($fileEntry=$d->read() )) {//copy one by one
//skip if it is navigation folder . or ..
if (in_array($fileEntry, $navFolders) ) {
continue;
}
//do copy
$s = "$source/$fileEntry";
$t = "$target/$fileEntry";
self::copy($s, $t);
}
$d->close();
}
}
Symfony를 사용하면 달성하기가 매우 쉽습니다.
$fileSystem = new Symfony\Component\Filesystem\Filesystem();
$fileSystem->mirror($from, $to);
See https://symfony.com/doc/current/components/filesystem.html
I clone entire directory by SPL Directory Iterator.
function recursiveCopy($source, $destination)
{
if (!file_exists($destination)) {
mkdir($destination);
}
$splFileInfoArr = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($splFileInfoArr as $fullPath => $splFileinfo) {
//skip . ..
if (in_array($splFileinfo->getBasename(), [".", ".."])) {
continue;
}
//get relative path of source file or folder
$path = str_replace($source, "", $splFileinfo->getPathname());
if ($splFileinfo->isDir()) {
mkdir($destination . "/" . $path);
} else {
copy($fullPath, $destination . "/" . $path);
}
}
}
#calling the function
recursiveCopy(__DIR__ . "/source", __DIR__ . "/destination");
// using exec
function rCopy($directory, $destination)
{
$command = sprintf('cp -r %s/* %s', $directory, $destination);
exec($command);
}
For Linux servers you just need one line of code to copy recursively while preserving permission:
exec('cp -a '.$source.' '.$dest);
Another way of doing it is:
mkdir($dest);
foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $item)
{
if ($item->isDir())
mkdir($dest.DIRECTORY_SEPARATOR.$iterator->getSubPathName());
else
copy($item, $dest.DIRECTORY_SEPARATOR.$iterator->getSubPathName());
}
but it's slower and does not preserve permissions.
참고URL : https://stackoverflow.com/questions/2050859/copy-entire-contents-of-a-directory-to-another-using-php
'Programing' 카테고리의 다른 글
프래그먼트에서 getSupportFragmentManager ()에 어떻게 액세스 할 수 있습니까? (0) | 2020.06.27 |
---|---|
필수 위조 방지 양식 필드 "__RequestVerificationToken"이 없습니다. 사용자 등록 오류 (0) | 2020.06.27 |
이진 검색 복잡성을 계산하는 방법 (0) | 2020.06.27 |
datetime.date.today ()를 조롱하려고 시도했지만 작동하지 않습니다. (0) | 2020.06.27 |
모든 저장 프로 시저에 실행 실행 (0) | 2020.06.26 |