JustinasT JustinasT - 7 months ago 9
PHP Question

Copying folder to other folder with PHP

I'm trying to move folder to other folder, with all it's files. Both folders are in root directory. Tried a lot of ways, and always get no result.
Here is my latest atempt:

$source = "template/"
$dest = "projects/"
function copyr($source, $dest){
if (is_link($source)) {
return symlink(readlink($source), $dest);
}

if (is_file($source)) {
return copy($source, $dest);
}
if (!is_dir($dest)) {
mkdir($dest);
}
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
copyr("$source/$entry", "$dest/$entry");
}
$dir->close();
return true;
}


Need professional glance to tell me, where I'm getting it wrong?

EDIT:

Sorry for wrong tags.
Problem is - nothing is happening. Nothing is being copied. No error messages. Simply nothing happens.
File structure:

enter image description here

Answer

I suggest to try and do the following

  1. How do you run the scrips? Do you open page in browser or run script in command line? If you open page in browser this might be an issue with permissions, paths (relative and not absolute) and errors not shown but logged.

  2. Use absolute folder paths instead of relative paths. For example /var/www/project/template.

Apply realpath() function to all paths and check (output) the result. If path is wrong (folder does not exist, separators are wrong etc) you will get empty result from the function.

Make sure to use DIRECTORY_SEPARATOR instead of / if you run your script on Windows. I can not check if / works on Windows now but potentially this might be an issue. For example

copyr($source.DIRECTORY_SEPARATOR.$entry", $dest.DIRECTORY_SEPARATOR.$entry);
  1. Check warnings and errors. If you do not have permission you should get warning like this

PHP Warning: mkdir(): Permission denied

You may need to enable warnings and errors if they are disabled. Try for example to make an obvious mistake with name and check if you get any error message.

  1. Try to use tested solution from one of the answers. For example xcopy function.

  2. Try to add debug messages or run your script in debugger step by step. Check what is happening, what is executed etc. You can add debug output near any operator like (just an idea):

    echo 'Creating directory '.$name.' ... '; mkdir($name); echo (is_dir($name) ? 'created' : 'failed').PHP_EOL;

Comments