tags:

views:

28

answers:

2

I am trying to copy all the files from a directory to another directory in php.

 $copy_all_files_from = "layouts/";
 $copy_to = "Website3/";

Can someone help me do this please.

A: 

Easiest:

`cp -r $copy_all_files_from $copy_to`

Unless you're on Windows. Without shelling, it's a bit more complex: read directory, iterate on files (if it's a directory, recurse), open each, iterate while not end of file, read block and write it.

UPDATE: doh, PHP has copy...

Amadan
I know. But it's still easiest, and sufficient for most purposes. And backticks are proper PHP. I did add what he needs to know in order to implement in pure PHP if he needs it.
Amadan
You don't have to open each file to read it and then write it, you can use copy(), see my comment ...
Rakward
Ah, you added it, I thought i had misread and deleted my comment, sorry
Rakward
+5  A: 

Something like this(untested):

<?php
$handle = opendir($copy_all_files_from);
while (false !== ($file = readdir($handle))) {
    copy( $file, $copy_to);
    }

edit:

To use Amadan's method, you should be able to use this php function: shell_exec();

Not sure since I never need to use server commands

Rakward
Definitely better than my reimplementing `copy` :) NB: Doesn't work for subdirectories.
Amadan
I gave him a starting point, figuring out the subdirectories will be a good way to learn for him :)
Rakward
To use @Amadan's method, you just need to type it like it is :) From the docs for shell_exec: "This function is identical to the backtick operator." Shell commands are useful since they are the most efficient at what they do, and tested for decades. Any reimplementation of, say recursive copy has an extremely low chance of beating `cp -r`.
Amadan
lol, I didn't know that. I'm an absolute n00b on unix stuff.
Rakward