mattew mattew - 5 months ago 17
PHP Question

Copy, elaborate and delete files in a directory. Which php iteration to use?

I admit, as a newbie I'm really confused on how to code an iterative process for the following operations.

Scenery: my file test.php checks the oldest .txt file in a specific directory and copies it into another directory called "backup". After this, the same file is elaborated by "elab.php" (updates a MySQL database with some data contained in the file) and successively delete it, after a sleep time of 4 seconds.

Here is the code:

$files = glob( '*.txt' );

array_multisort(
array_map( 'filemtime', $files ),
SORT_NUMERIC,
SORT_ASC,
$files
);

$filename="$files[0]";

copy($filename,"./backup/$filename");
echo "<b> $filename </b>copied<br>";

include ("/home/mysite/directory/elab.php");

sleep(4);

unlink($filename);


As in the directory there is more than one .txt file, i'd like to perform a recursive process. It should repeat the operation for all .txt files until the directory becomes empty. How to do?
I'm confused because i don't know if it is better to use "foreach" or "if" or "while". Which is the best one? How to modify the file with the recursive check?

Thank you in advance for your help.

Mat

Answer
$files = scandir('folder/');
foreach($files as $file) {
  //do your work here
}

or

$files = glob('folder/*.{txt}', GLOB_BRACE);
foreach($files as $file) {
  //do your work here
}