php shell_exec: как скопировать каталог от одного пользователя к другому (VPS на CentOs5)

При работе на CentOS5 + DirectAdmin.

У меня есть VPS, но из соображений безопасности я просто хочу предоставить все управление только пользователю-посреднику.

С пользователем реселлера у меня есть скрипт, который подключается к DA реселлера и создает пользователя.

Моя проблема заключается в том, как скопировать дерево каталогов с ~ 10000 файлов, которое находится в 'пользователь посредников' ftp, ex. /domains/hoster.dom.com/public_html/dir_to_be_copied

новому созданному пользователю, пароль и имя которого я знаю.

Насколько я понимаю, это должно быть возможно сделать как внутреннее действие сервера с помощью команды «shell_exec()».

Кроме того, что такое команда для входа другого пользователя FTP и работы с его файлами. И можно ли одновременно подключаться к двум фтп пользователям и делать копии с одного на другого.

  • Я знаю, что может быть предложено делать это ведение журнала от имени пользователя «root», но, возможно, это возможно без доступа к пользователю «root».

Спасибо.


person ozzWANTED    schedule 24.06.2010    source источник


Ответы (1)


<?php
/**
 * Copy file or folder from source to destination, it can do
 * recursive copy as well and is very smart
 * It recursively creates the dest file or directory path if there weren't exists
 * Situtaions :
 * - Src:/home/test/file.txt ,Dst:/home/test/b ,Result:/home/test/b -> If source was file copy file.txt name with b as name to destination
 * - Src:/home/test/file.txt ,Dst:/home/test/b/ ,Result:/home/test/b/file.txt -> If source was file Creates b directory if does not exsits and copy file.txt into it
 * - Src:/home/test ,Dst:/home/ ,Result:/home/test/** -> If source was directory copy test directory and all of its content into dest     
 * - Src:/home/test/ ,Dst:/home/ ,Result:/home/**-> if source was direcotry copy its content to dest
 * - Src:/home/test ,Dst:/home/test2 ,Result:/home/test2/** -> if source was directoy copy it and its content to dest with test2 as name
 * - Src:/home/test/ ,Dst:/home/test2 ,Result:->/home/test2/** if source was directoy copy it and its content to dest with test2 as name
 * @todo
 *     - Should have rollback technique so it can undo the copy when it wasn't successful
 *  - Auto destination technique should be possible to turn off
 *  - Supporting callback function
 *  - May prevent some issues on shared enviroments : http://us3.php.net/umask
 * @param $source //file or folder
 * @param $dest ///file or folder
 * @param $options //folderPermission,filePermission
 * @return boolean
 */
function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755))
{
    $result=false;

    if (is_file($source)) {
        if ($dest[strlen($dest)-1]=='/') {
            if (!file_exists($dest)) {
                cmfcDirectory::makeAll($dest,$options['folderPermission'],true);
            }
            $__dest=$dest."/".basename($source);
        } else {
            $__dest=$dest;
        }
        $result=copy($source, $__dest);
        chmod($__dest,$options['filePermission']);

    } elseif(is_dir($source)) {
        if ($dest[strlen($dest)-1]=='/') {
            if ($source[strlen($source)-1]=='/') {
                //Copy only contents
            } else {
                //Change parent itself and its contents
                $dest=$dest.basename($source);
                @mkdir($dest);
                chmod($dest,$options['filePermission']);
            }
        } else {
            if ($source[strlen($source)-1]=='/') {
                //Copy parent directory with new name and all its content
                @mkdir($dest,$options['folderPermission']);
                chmod($dest,$options['filePermission']);
            } else {
                //Copy parent directory with new name and all its content
                @mkdir($dest,$options['folderPermission']);
                chmod($dest,$options['filePermission']);
            }
        }

        $dirHandle=opendir($source);
        while($file=readdir($dirHandle))
        {
            if($file!="." && $file!="..")
            {
                 if(!is_dir($source."/".$file)) {
                    $__dest=$dest."/".$file;
                } else {
                    $__dest=$dest."/".$file;
                }
                //echo "$source/$file ||| $__dest<br />";
                $result=smartCopy($source."/".$file, $__dest, $options);
            }
        }
        closedir($dirHandle);

    } else {
        $result=false;
    }
    return $result;
}
?>

http://www.php.net/manual/en/function.copy.php#91256

person Marco Ceppi    schedule 25.06.2010
comment
Я знаю, что этому уже почти 4 года, но я должен сказать вам, что все другие рекурсивные копии, которые я пробовал, медленно перемещали установку WordPress. Эта штука - бам! Миллисекунды и готово. Вот почему я поставил +1. Спасибо Марко за отличную функцию! - person MrTechie; 28.02.2014