Thursday, 30 August 2018

PHP moves the selected files from folder A to folder B

This is a tricky one and I'm not sure where to start, so any help will be grateful.

I have a parent folder called 'source' (c:/dev/source) which contains several child folders.
I need a PHP script that will display the child folders with checkboxes next to each, and a text field for a new folder name, allowing users to tick the checkboxes of the ones they want to copy to a 'destination of c:/dev/destination/the_folder_name_they_typed_in
When they click submit, the selected child folders will be copied from c:/dev/source to c:/dev/destination/the_folder_name_they_typed_in
This is all running on a local internal development server. The child folders will always be in c:/dev/source/

Here's a not well known little bit of code called DirectoryIterator. It's not fully documented on the PHP site, but heres the jist of it:
Create a list of files and folders with checkboxes next to them, slap them all in an array.
$Directory = new RecursiveDirectoryIterator('c:/dev/source');
$Iterator = new RecursiveIteratorIterator($Directory);    

?><form method="post"><?
foreach($Iterator  as $r){

       if($r->isDot()) continue;

       echo "<input type=\"checkbox\" name=\"copy[]\" value=\"".($r->getSubPathName())."\"> ".$r->getSubPathName() . " <br>";

}
?></form><?


Now add this part to the top of the file
<?php
if($_POST){
if(is_array($_POST['copy'])) foreach($_POST['copy'] as $c){
 @copy($c, str_replace('c:/dev/source','c:/dev/dest', $c));
  echo "copied: $c to ". str_replace('c:/dev/source','c:/dev/dest', $c) . "<br>";

}
}

I'm not fully sure what result you get from $r->getSubPathName() can you let me know if it outputs an array? if so it might be that you replace that with $r->getSubPath() and then add the "c:/dev/source" to the variable $c when you copy it?

Further Reading:

0 comments:

Post a Comment