Rajanikant
Rajanikant

Reputation: 31

copy file from one folder to other

I want to move all files from one folder to other. my code is as following. in this I made a folder in which i want to copy all file from templats folder

$doit = str_replace(" ", "", $slt['user_compeny_name']);
mkdir("$doit");
$source = "templat/";
$target = $doit . "/";
$dir = opendir($source);
while (($file = readdir($dir)) !== false) {
    copy($source . $file, $target . $file);
}

It working fine . copy all files but give warning that The first argument to copy() function cannot be a directory

can any one help me asap

Upvotes: 0

Views: 3284

Answers (5)

stixxx
stixxx

Reputation: 56

I know, this question is pretty old, but also are the answers. I feel the need to show some new methods, which can be used to execute the requested task.

In the mean time Objects were introduced with a lot more features and possibilities. Needless to say, the other answers will still work aswell.

But here we go, using the DirectoryIterator:

$szSrcFolder = 'source_folder';
$szTgtFolder = 'target_folder';

foreach (new DirectoryIterator($szSrcFolder) as $oInfo)
    if ($oInfo->isFile())
        copy($oInfo->getPathname(), $szTgtFolder . DIRECTORY_SEPARATOR . $oInfo->getBasename());

Remember, within this script, all paths are relative to the working directory of the script itself.

I think it is self explaining, but we will take a look. This few lines will iterate over the whole content of the source folder and check if it is a file and will copy it to the target folder, keeping the original file name.

Upvotes: 1

Alexey
Alexey

Reputation: 158

if ($file != "." && $file != "..") {
// copy
}

Upvotes: 3

jezmck
jezmck

Reputation: 1149

opendir() will include items . and .. as per the documentation.

You will need to exclude these by using the code in the other comments.

Upvotes: 3

Anthony
Anthony

Reputation: 37065

You are not accounting for the . and the .. files at the top of the directory. This means that the first thing it tries to copy is "\template." which would be the same as trying to copy the directory.

Just add something like:

if ($file !== "." && $file !== "..")
...

Upvotes: 3

Duroth
Duroth

Reputation: 6581

Readdir will read all children in a directory, including other dirs, and 'virtual' dirs like . and .. (link to root and parent dir, resp.) You'll have to check for these and prevent the copy() function for these instances.

while (($file = readdir($dir)) !== false)
{
    if(!is_dir($file))
    {
        copy($source.$file, $target.$file);
    }
}

Upvotes: 4

Related Questions