How to copy a file from one directory to another using PHP?

后端 未结 8 880
暗喜
暗喜 2020-11-28 06:38

Say I\'ve got a file test.php in foo directory as well as bar. How can I replace bar/test.php with foo/test.php

相关标签:
8条回答
  • 2020-11-28 07:12

    Best way to copy all files from one folder to another using PHP

    <?php
    $src = "/home/www/example.com/source/folders/123456";  // source folder or file
    $dest = "/home/www/example.com/test/123456";   // destination folder or file        
    
    shell_exec("cp -r $src $dest");
    
    echo "<H2>Copy files completed!</H2>"; //output when done
    ?>
    
    0 讨论(0)
  • 2020-11-28 07:14

    copy will do this. Please check the php-manual. Simple Google search should answer your last two questions ;)

    0 讨论(0)
  • 2020-11-28 07:14

    You can copy and past this will help you

    <?php
    $file = '/test1/example.txt';
    $newfile = '/test2/example.txt';
    if(!copy($file,$newfile)){
        echo "failed to copy $file";
    }
    else{
        echo "copied $file into $newfile\n";
    }
    ?>
    
    0 讨论(0)
  • 2020-11-28 07:14

    You can use both rename() and copy().

    I tend to prefer to use rename if I no longer require the source file to stay in its location.

    0 讨论(0)
  • 2020-11-28 07:15

    You could use the rename() function :

    rename('foo/test.php', 'bar/test.php');
    

    This however will move the file not copy

    0 讨论(0)
  • 2020-11-28 07:19

    You could use the copy() function :

    // Will copy foo/test.php to bar/test.php
    // overwritting it if necessary
    copy('foo/test.php', 'bar/test.php');
    


    Quoting a couple of relevant sentences from its manual page :

    Makes a copy of the file source to dest.

    If the destination file already exists, it will be overwritten.

    0 讨论(0)
提交回复
热议问题