Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 378
  • Last Modified:

PHP Copying files

I need to make a copy a a file and a folder using php.

the situation -

I have a file called 12345.json and a folder called 12345 with several images

I want to copy the file 12345.json to 12345-1.json and the folder to 12345-1

Can anyone please point me in the right direction.

Thank You.
0
JefferyBraun
Asked:
JefferyBraun
1 Solution
 
Dan CraciunIT ConsultantCommented:
Here's a xcopy function, taken from here:
Simply add that to your code, then call it like:
xcopy("12345", "12345-1");
xcopy("12345.json", "12345-1.json");
/**
 * Copy a file, or recursively copy a folder and its contents
 * @param       string   $source    Source path
 * @param       string   $dest      Destination path
 * @param       string   $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");
    }

    // Clean up
    $dir->close();
    return true;
}

Open in new window

0
 
JefferyBraunAuthor Commented:
Thank You very much. This will do the trick.
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now