0

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

5 Answers 5

4

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); } } 
Sign up to request clarification or add additional context in comments.

Comments

3

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 !== "..") ... 

Comments

3

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

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

Comments

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

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.