Search code examples
phpcopydirectoryfile-rename

Best way to move entire directory tree in PHP


I would like to move a file from one directory to another. However, the trick is, I want to move file with entire path to it.

Say I have file at

/my/current/directory/file.jpg

and I would like to move it to

/newfolder/my/current/directory/file.jpg

So as you can see I want to retain the relative path so in the future I can move it back to /my/current/directory/ if I so require. One more thing is that /newfolder is empty - I can copy anything in there so there is no pre-made structure (another file may be copied to /newfolder/my/another/folder/anotherfile.gif. Ideally I would like to be able to create a method that will do the magic when I pass original path to file to it. Destination is always the same - /newfolder/...


Solution

  • You may try something like this if you're in an unix/linux environment :

    $original_file = '/my/current/directory/file.jpg';
    $new_file = "/newfolder{$original_file}";
    
    // create new diretory stricture (note the "-p" option of mkdir)
    $new_dir = dirname($new_file);
    if (!is_dir($new_dir)) {
        $command = 'mkdir -p ' . escapeshellarg($new_dir);
        exec($command);
    }
    
    echo rename($original_file, $new_file) ? 'success' : 'failed';