I need to create a loop through all files in subdirectories. Can you please help me struct my code like this:
$main = "MainDirectory";
loop through sub-directories {
loop through filels in each sub-directory {
do something with each file
}
};
Use RecursiveDirectoryIterator in conjunction with RecursiveIteratorIterator.
$di = new RecursiveDirectoryIterator('path/to/directory');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
}
You need to add the path to your recursive call.
function readDirs($path){
$dirHandle = opendir($path);
while($item = readdir($dirHandle)) {
$newPath = $path."/".$item;
if(is_dir($newPath) && $item != '.' && $item != '..') {
echo "Found Folder $newPath<br>";
readDirs($newPath);
}
else{
echo ' Found File or .-dir '.$item.'<br>';
}
}
}
$path = "/";
echo "$path<br>";
readDirs($path);
You probably want to use a recursive function for this, in case your sub directories have sub-sub directories
$main = "MainDirectory";
function readDirs($main){
$dirHandle = opendir($main);
while($file = readdir($dirHandle)){
if(is_dir($main . $file) && $file != '.' && $file != '..'){
readDirs($file);
}
else{
//do stuff
}
}
}
didn't test the code, but this should be close to what you want.
I like glob with it's wildcards :
foreach (glob("*/*.txt") as $filename) {
echo "$filename\n";
}
Details and more complex scenarios.
But if You have a complex folders structure RecursiveDirectoryIterator is definitively the solution.
Come on, first try it yourself!
What you'll need:
scandir()
is_dir()
and of course foreach
http://php.net/manual/en/function.is-dir.php
http://php.net/manual/en/function.scandir.php
Another solution to read with sub-directories and sub-files (set correct foldername):
<?php
$path = realpath('samplefolder/yorfolder');
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename)
{
echo "$filename <br/>";
}
?>
Minor modification on what John Marty posted, if we can safely eliminate any items that are named . or ..
function readDirs($path){
$dirHandle = opendir($path);
while($item = readdir($dirHandle)) {
$newPath = $path."/".$item;
if (($item == '.') || ($item == '..')) {
continue;
}
if (is_dir($newPath)) {
pretty_echo('Found Folder '.$newPath);
readDirs($newPath);
} else {
pretty_echo('Found File: '.$item);
}
}
}
function pretty_echo($text = '')
{
echo $text;
if (PHP_OS == 'Linux') {
echo "\r\n";
}
else {
echo "</br>";
}
}
<?php
ini_set('max_execution_time', 300); // increase the execution time of the file (in case the number of files or file size is more).
class renameNewFile {
static function copyToNewFolder() { // copies the file from one location to another.
$main = 'C:\xampp\htdocs\practice\demo'; // Source folder (inside this folder subfolders and inside each subfolder files are present.)
$main1 = 'C:\xampp\htdocs\practice\demomainfolder'; // Destination Folder
$dirHandle = opendir($main); // Open the source folder
while ($file = readdir($dirHandle)) { // Read what's there inside the source folder
if (basename($file) != '.' && basename($file) != '..') { // Ignore if the folder name is '.' or '..'
$folderhandle = opendir($main . '\\' . $file); // Open the Sub Folders inside the Main Folder
while ($text = readdir($folderhandle)) {
if (basename($text) != '.' && basename($text) != '..') { // Ignore if the folder name is '.' or '..'
$filepath = $main . '\\' . $file . '\\' . $text;
if (!copy($filepath, $main1 . '\\' . $text)) // Copy the files present inside the subfolders to destination folder
echo "Copy failed";
else {
$fh = fopen($main1 . '\\' . 'log.txt', 'a'); // Write a log file to show the details of files copied.
$text1 = str_replace(' ', '_', $text);
$data = $file . ',' . strtolower($text1) . "\r\n";
fwrite($fh, $data);
echo $text . " is copied <br>";
}
}
}
}
}
}
static function renameNewFileInFolder() { //Renames the files into desired name
$main1 = 'C:\xampp\htdocs\practice\demomainfolder';
$dirHandle = opendir($main1);
while ($file = readdir($dirHandle)) {
if (basename($file) != '.' && basename($file) != '..') {
$filepath = $main1 . '\\' . $file;
$text1 = strtolower($filepath);
rename($filepath, $text1);
$text2 = str_replace(' ', '_', $text1);
if (rename($filepath, $text2))
echo $filepath . " is renamed to " . $text2 . '<br/>';
}
}
}
}
renameNewFile::copyToNewFolder();
renameNewFile::renameNewFileInFolder();
?>
$allFiles = [];
public function dirIterator($dirName)
{
$whatsInsideDir = scandir($dirName);
foreach ($whatsInsideDir as $fileOrDir) {
if (is_dir($fileOrDir)) {
dirIterator($fileOrDir);
}
$allFiles.push($fileOrDir);
}
return $allFiles;
}
Related
I'm trying to search for a folder and retrieve the files inside of the folder (get content) I'm able to search for the folder using the follow code but I can't pass from there I can't see the content an retrieve the files inside. The files inside will be txt files and I would like to be able to open and see then.
How can achieve what i want? Thank you.
<?php
$dirname = "C:\windows";//Directory to search in. *Must have a trailing slash*
$findme = $_POST["search"];
$dir = opendir($dirname);
while(false != ($file = readdir($dir))){//Loop for every item in the directory.
if(($file != ".") and ($file != "..") and ($file != ".DS_Store") and ($file !=
"search.php"))//Exclude these files from the search
{
$pos = stripos($file, $findme);
if ($pos !== false){
$thereisafile = true;//Tell the script something was found.
echo'' . $file . '<br>';
}else{
}
}
}
if (!isset($thereisafile)){
echo "Nothing was found.";//Tell the user nothing was found.
echo '<img src="yourimagehere.jpg"/>';//Display an image, when nothing was found.
}
?>
New code
<?php
$dirname = "C:\\Windows\\";//Directory to search in. *Must have a trailing slash*
$findme = 'maxlink'; //$_POST["search"];
$files = scandir($dirname);
foreach ($files AS $file)
{
if ($file == '.' or $file == '..' or $file == '.DS_Store' or $file == 'search.php') continue;
if (stripos($file, $findme) !== false)
{
$found = true;
echo 'FOUND FILE ' . $file . '<hr>';
echo 'OPENING IT:<br>';
echo file_get_contents($dirname . $file);
echo '<hr>';
}
else
{
echo 'not found: ' . $file . '<br>';
}
}
if (!isset($found))
{
echo "Nothing was found.";//Tell the user nothing was found.
echo '<img src="yourimagehere.jpg"/>';//Display an image, when nothing was found.
}
The following code uses a recursive function for searching the directory. I hope it’ll solve your problem.
function scandir_r($dir){
$files = array_diff(scandir($dir), array(".", ".."));
$arr = array();
foreach($files as $file){
$arr[] = $dir.DIRECTORY_SEPARATOR.$file;
if(is_dir($dir.DIRECTORY_SEPARATOR.$file)){
$arr = array_merge($arr, scandir_r($dir.DIRECTORY_SEPARATOR.$file));
}
}
return($arr);
}
$dirname = "C:\windows";
$findme = "/".preg_quote($_POST["search"], "/")."/";
$files = preg_grep($findme, scandir_r($dirname));
if(sizeof($files)){
foreach($files as $file){
$_file = $dirname.DIRECTORY_SEPARATOR.$file;
echo "$file<br/>";
}
}
else{
echo "Nothing was found.";
echo "<img src=\"yourimagehere.jpg\"/>";
}
I have a folder on my server called 'images', and within that folder I could have a single folder to as many as 10 folders that contain images.
Instead of writing a tag for each image
<img src="images/people/001.jpg">
<img src="images/landscape/001.jpg">
etc etc
Can I use PHP to get all the images in all the folders in the main directory 'images'?
I have VERY little experience with PHP, so this is something I am struggling with.
I need php to return an array of '<div class="box"><img src="images/FOLDER/IMAGENAME.jpg"></div>'
Maybe someone can help.
function ListFiles($dir) {
if($dh = opendir($dir)) {
$files = Array();
$inner_files = Array();
while($file = readdir($dh)) {
if($file != "." && $file != ".." && $file[0] != '.') {
if(is_dir($dir . "/" . $file)) {
$inner_files = ListFiles($dir . "/" . $file);
if(is_array($inner_files)) $files = array_merge($files, $inner_files);
} else {
array_push($files, $dir . "/" . $file);
}
}
}
closedir($dh);
return $files;
}
}
foreach (ListFiles('/path/to/images') as $key=>$file){
echo "<div class=\"box\"><img src=\"$file\"/></div>";
}
Something like this?
A simpler soluton. You can use built-in glob function. Assuming that all of your images are .jpg:
$result = array();
$dir = 'images/';
foreach(glob($dir.'*.jpg') as $filename) {
$result[] = "<div class=\"box\"><img src=\"$filename\"></div>";
}
Then you can echo each element of $result or whatever you want.
On my old VPS I was using the following code to copy the files and directories within a directory to a new directory that was created after the user submitted their form.
function copyr($source, $dest)
{
// Simple copy for a file
if (is_file($source)) {
return copy($source, $dest);
}
// Make destination directory
if (!is_dir($dest)) {
mkdir($dest);
$company = ($_POST['company']);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Deep copy directories
if ($dest !== "$source/$entry") {
copyr("$source/$entry", "$dest/$entry");
}
}
// Clean up
$dir->close();
return true;
}
copyr('Template/MemberPages', "Members/$company")
However now on my new VPS it will only create the main directory, but will not copy any of the files to it. I don't understand what could have changed between the 2 VPS's?
Try something like this:
$source = "dir/dir/dir";
$dest= "dest/dir";
mkdir($dest, 0755);
foreach (
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST) as $item
) {
if ($item->isDir()) {
mkdir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
} else {
copy($item, $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathname());
}
}
Iterator iterate through all folders and subfolders and make copy of files from $source to $dest
Could I suggest that (assuming it's a *nix VPS) that you just do a system call to cp -r and let that do the copy for you.
This function copies folder recursivley very solid. I've copied it from the comments section on copy command of php.net
function recurse_copy($src,$dst) {
$dir = opendir($src);
#mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
I have changed Joseph's code (below), because it wasn't working for me. This is what works:
function cpy($source, $dest){
if(is_dir($source)) {
$dir_handle=opendir($source);
while($file=readdir($dir_handle)){
if($file!="." && $file!=".."){
if(is_dir($source."/".$file)){
if(!is_dir($dest."/".$file)){
mkdir($dest."/".$file);
}
cpy($source."/".$file, $dest."/".$file);
} else {
copy($source."/".$file, $dest."/".$file);
}
}
}
closedir($dir_handle);
} else {
copy($source, $dest);
}
}
[EDIT] added test before creating a directory (line 7)
The Symfony's FileSystem Component offers a good error handling as well as recursive remove and other useful stuffs. Using #OzzyCzech's great answer, we can do a robust recursive copy this way:
use Symfony\Component\Filesystem\Filesystem;
// ...
$fileSystem = new FileSystem();
if (file_exists($target))
{
$this->fileSystem->remove($target);
}
$this->fileSystem->mkdir($target);
$directoryIterator = new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS);
$iterator = new \RecursiveIteratorIterator($directoryIterator, \RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $item)
{
if ($item->isDir())
{
$fileSystem->mkdir($target . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
}
else
{
$fileSystem->copy($item, $target . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
}
}
Note: you can use this component as well as all other Symfony2 components standalone.
Here's what we use at our company:
static public function copyr($source, $dest)
{
// recursive function to copy
// all subdirectories and contents:
if(is_dir($source)) {
$dir_handle=opendir($source);
$sourcefolder = basename($source);
mkdir($dest."/".$sourcefolder);
while($file=readdir($dir_handle)){
if($file!="." && $file!=".."){
if(is_dir($source."/".$file)){
self::copyr($source."/".$file, $dest."/".$sourcefolder);
} else {
copy($source."/".$file, $dest."/".$file);
}
}
}
closedir($dir_handle);
} else {
// can also handle simple copy commands
copy($source, $dest);
}
}
function recurse_copy($source, $dest)
{
// Check for symlinks
if (is_link($source)) {
return symlink(readlink($source), $dest);
}
// Simple copy for a file
if (is_file($source)) {
return copy($source, $dest);
}
// Make destination directory
if (!is_dir($dest)) {
mkdir($dest);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Deep copy directories
recurse_copy("$source/$entry", "$dest/$entry");
}
// Clean up
$dir->close();
return true;
}
OzzyCheck's is elegant and original, but he forgot the initial mkdir($dest);
See below. No copy command is ever provided with contents only. It must fulfill its entire role.
$source = "dir/dir/dir";
$dest= "dest/dir";
mkdir($dest, 0755);
foreach (
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST) as $item) {
if ($item->isDir()) {
mkdir($dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
} else {
copy($item, $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
}
}
Here's a simple recursive function to copy entire directories
source: http://php.net/manual/de/function.copy.php
<?php
function recurse_copy($src,$dst) {
$dir = opendir($src);
#mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
copy($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
?>
Why not just ask the OS to take care of this?
system("cp -r olddir newdir");
Done.
<?php
/**
* code by Nk (nk.have.a#gmail.com)
*/
class filesystem
{
public static function normalizePath($path)
{
return $path.(is_dir($path) && !preg_match('#/$#', $path) ? '/' : '');
}
public static function rscandir($dir, $sort = SCANDIR_SORT_ASCENDING)
{
$results = array();
if(!is_dir($dir))
return $results;
$dir = self::normalizePath($dir);
$objects = scandir($dir, $sort);
foreach($objects as $object)
if($object != '.' && $object != '..')
{
if(is_dir($dir.$object))
$results = array_merge($results, self::rscandir($dir.$object, $sort));
else
array_push($results, $dir.$object);
}
array_push($results, $dir);
return $results;
}
public static function rcopy($source, $dest, $destmode = null)
{
$files = self::rscandir($source);
if(empty($files))
return;
if(!file_exists($dest))
mkdir($dest, is_int($destmode) ? $destmode : fileperms($source), true);
$source = self::normalizePath(realpath($source));
$dest = self::normalizePath(realpath($dest));
foreach($files as $file)
{
$file_dest = str_replace($source, $dest, $file);
if(is_dir($file))
{
if(!file_exists($file_dest))
mkdir($file_dest, is_int($destmode) ? $destmode : fileperms($file), true);
}
else
copy($file, $file_dest);
}
}
}
?>
/var/www/websiteA/backup.php :
<?php /* include.. */ filesystem::rcopy('/var/www/websiteA/', '../websiteB'); ?>
hmm. as that's complicated ))
function mkdir_recursive( $dir ){
$prev = dirname($dir);
if( ! file_exists($prev))
{
mkdir_recursive($prev);
}
if( ! file_exists($dir))
{
mkdir($dir);
}
}
...
$srcDir = "/tmp/from"
$dstDir = "/tmp/to"
mkdir_recursive($dstDir);
foreach( $files as $file){
copy( $srcDir."/".$file, $dstDir."/".$file);
}
$file - somthing like that file.txt
I guess you should check user(group)rights. You should consider chmod for example, depending on how you run (su?)PHP. You could possibly also choose to modify your php configuration.
There were some issues with the functions that I tested in the thread and here is a powerful function that covers everything. Highlights:
No need to have an initial or intermediate source directories. All of the directories up to the source directory and to the copied directories will be handled.
Ability to skip directory or files from an array. (optional) With the global $skip; skipping of files even under sub level directories are handled.
Full recursive support, all the files and directories in multiple depth are supported.
$from = "/path/to/source_dir";
$to = "/path/to/destination_dir";
$skip = array('some_file.php', 'somedir');
copy_r($from, $to, $skip);
function copy_r($from, $to, $skip=false) {
global $skip;
$dir = opendir($from);
if (!file_exists($to)) {mkdir ($to, 0775, true);}
while (false !== ($file = readdir($dir))) {
if ($file == '.' OR $file == '..' OR in_array($file, $skip)) {continue;}
if (is_dir($from . DIRECTORY_SEPARATOR . $file)) {
copy_r($from . DIRECTORY_SEPARATOR . $file, $to . DIRECTORY_SEPARATOR . $file);
}
else {
copy($from . DIRECTORY_SEPARATOR . $file, $to . DIRECTORY_SEPARATOR . $file);
}
}
closedir($dir);
}
Recursively copies files from source to target, with choice of overwriting existing files on the target.
function copyRecursive($sourcePath, $targetPath, $overwriteExisting) {
$dir = opendir($sourcePath);
while (($file = readdir($dir)) !== false) {
if ($file == "." || $file == "..") continue; // ignore these.
$source = $sourcePath . "/" . $file;
$target = $targetPath. "/" . $file;
if (is_dir($source) == true) {
// create the target directory, if it does not exist.
if (file_exists($target) == false) #mkdir($target);
copyRecursive($source, $target, $overwriteExisting);
} else {
if ((file_exists($target) == false) || ($overwriteExisting == true)) {
copy($source, $target);
}
}
}
closedir($dir);
}
This question already has answers here:
Getting the names of all files in a directory with PHP
(15 answers)
Closed 6 months ago.
I have the code below that lists all the images in a folder, the problem is that it finds some files ( a . and a ..) that I am not sure what they are so I am not sure how to prevent them from showing up. I am on a windows XP machine, any help would be great, thanks.
Errors: Warning: rename(images/.,images/.) [function.rename]: No error
in C:\wamp\www\Testing\listPhotosA.php on line 14
Warning: rename(images/..,images/..) [function.rename]: No error in
C:\wamp\www\Testing\listPhotosA.php on line 14
Code:
<?php
define('IMAGEPATH', 'images/');
if (is_dir(IMAGEPATH)){
$handle = opendir(IMAGEPATH);
}
else{
echo 'No image directory';
}
$directoryfiles = array();
while (($file = readdir($handle)) !== false) {
$newfile = str_replace(' ', '_', $file);
rename(IMAGEPATH . $file, IMAGEPATH . $newfile);
$directoryfiles[] = $newfile;
}
foreach($directoryfiles as $directoryfile){
if(strlen($directoryfile) > 3){
echo '<img src="' . IMAGEPATH . $directoryfile . '" alt="' . $directoryfile . '" /> <br>';
}
}
closedir($handle); ?>
I like PHP's glob function.
foreach(glob(IMAGEPATH.'*') as $filename){
echo basename($filename) . "\n";
}
glob() is case sensitive and the wildcard * will return all files, so I specified the extension here so you don't have to do the filtering work
$d = 'path/to/images/';
foreach(glob($d.'*.{jpg,JPG,jpeg,JPEG,png,PNG}',GLOB_BRACE) as $file){
$imag[] = basename($file);
}
Use glob function.
<?php
define('IMAGEPATH', 'images/');
foreach(glob(IMAGEPATH.'*') as $filename){
$imag[] = basename($filename);
}
print_r($imag);
?>
You got all images in array format
To get all jpg images in all dirs and subdirs inside a folder:
function getAllDirs($directory, $directory_seperator) {
$dirs = array_map(function ($item) use ($directory_seperator) {
return $item . $directory_seperator;
}, array_filter(glob($directory . '*'), 'is_dir'));
foreach ($dirs AS $dir) {
$dirs = array_merge($dirs, getAllDirs($dir, $directory_seperator));
}
return $dirs;
}
function getAllImgs($directory) {
$resizedFilePath = array();
foreach ($directory AS $dir) {
foreach (glob($dir . '*.jpg') as $filename) {
array_push($resizedFilePath, $filename);
}
}
return $resizedFilePath;
}
$directory = "C:/xampp/htdocs/images/";
$directory_seperator = "/";
$allimages = getAllImgs(getAllDirs($directory, $directory_seperator));
Using balphp's scan_dir function:
https://github.com/balupton/balphp/blob/765ee3cfc4814ab05bf3b5512b62b8b984fe0369/lib/core/functions/_scan_dir.funcs.php
scan_dir($dirPath, array('pattern'=>'image'));
Will return an array of all files that are images in that path and all subdirectories, using a $path => $filename structure. To turn off scanning subdirectories, set the recurse option to false
Please use the following code to read images from the folder.
function readDataFromImageFolder() {
$imageFolderName = 14;
$base = dirname(__FILE__);
$dirname = $base.DS.'images'.DS.$imageFolderName.DS;
$files = array();
if (!file_exists($dirname)) {
echo "The directory $dirname not exists.".PHP_EOL;
exit;
} else {
echo "The directory $dirname exists.".PHP_EOL;
$dh = opendir( $dirname );
while (false !== ($filename = readdir($dh))) {
if ($filename === '.' || $filename === '..') continue;
$files[] = $dirname.$filename;
}
uploadImages( $files );
}
}
Please click here for detailed explanation.
http://www.pearlbells.co.uk/code-snippets/read-images-folder-php/
You can use OPP oriented DirectoryIterator class.
foreach (new DirectoryIterator(IMAGEPATH) as $fileInfo) {
// Removing dots
if($fileInfo->isDot()) {
continue;
}
// You have all necessary data in $fileInfo
echo $fileInfo->getFilename() . "<br>\n";
}
while (($file = readdir($handle)) !== false) {
if (
($file == '.')||
($file == '..')
) {
continue;
}
$newfile = str_replace(' ', '_', $file);
rename(IMAGEPATH . $file, IMAGEPATH . $newfile);
$directoryfiles[] = $newfile;
}
I am using windows, Mysql DB, PHP
I am building the Joomla Component whose one of the functionality is to synchronize the folders
I want to sync two folders of different name.. How can I do this? It has to be dne in the same machine, no two different servers are involved in it..
How to sync two folders in PHP?
UPDATED
IN Context of Alex Reply
What if i am editing any .jpg file in one folder and saving it with same name as it has, also this file is already present in other folder. And I want this edited pic to be transfered to the other folder.? also I have Joomla's nested file structured to be compared
UPDATE 2
I have a recursive function which will output me the complete structure of folder... if u can just use it to concat ur solution in...
<?
function getDirectory($path = '.', $ignore = '') {
$dirTree = array ();
$dirTreeTemp = array ();
$ignore[] = '.';
$ignore[] = '..';
$dh = #opendir($path);
while (false !== ($file = readdir($dh))) {
if (!in_array($file, $ignore)) {
if (!is_dir("$path/$file")) {
$stat = stat("$path/$file");
$statdir = stat("$path");
$dirTree["$path"][] = $file. " === ". date('Y-m-d H:i:s', $stat['mtime']) . " Directory == ".$path."===". date('Y-m-d H:i:s', $statdir['mtime']) ;
} else {
$dirTreeTemp = getDirectory("$path/$file", $ignore);
if (is_array($dirTreeTemp))$dirTree = array_merge($dirTree, $dirTreeTemp);
}
}
}
closedir($dh);
return $dirTree;
}
$ignore = array('.htaccess', 'error_log', 'cgi-bin', 'php.ini', '.ftpquota');
$dirTree = getDirectory('.', $ignore);
?>
<pre>
<?
print_r($dirTree);
?>
</pre>
I just ran this, and it seems to work
function sync() {
$files = array();
$folders = func_get_args();
if (empty($folders)) {
return FALSE;
}
// Get all files
foreach($folders as $key => $folder) {
// Normalise folder strings to remove trailing slash
$folders[$key] = rtrim($folder, DIRECTORY_SEPARATOR);
$files += glob($folder . DIRECTORY_SEPARATOR . '*');
}
// Drop same files
$uniqueFiles = array();
foreach($files as $file) {
$hash = md5_file($file);
if ( ! in_array($hash, $uniqueFiles)) {
$uniqueFiles[$file] = $hash;
}
}
// Copy all these unique files into every folder
foreach($folders as $folder) {
foreach($uniqueFiles as $file => $hash) {
copy($file, $folder . DIRECTORY_SEPARATOR . basename($file));
}
}
return TRUE;
}
// usage
sync('sync', 'sync2');
You simply give it a list of folders to sync, and it will sync all files. It will attempt to skip files that appear the same (i.e. of whom their hash collides).
This however does not take into account last modified dates or anything. You will have to modify itself to do that. It should be pretty simple, look into filemtime().
Also, sorry if the code sucks. I had a go at making it recursive, but I failed :(
For a one way copy, try this
$source = '/path/to/source/';
$destination = 'path/to/destination/';
$sourceFiles = glob($source . '*');
foreach($sourceFiles as $file) {
$baseFile = basename($file);
if (file_exists($destination . $baseFile)) {
$originalHash = md5_file($file);
$destinationHash = md5_file($destination . $baseFile);
if ($originalHash === $destinationHash) {
continue;
}
}
copy($file, $destination . $baseFile);
}
It sounds like you just want to copy all files from one folder to another. The second example will do this.
I using this, and it seems to work, also make new dir if not exist .....
//sync the files and folders
function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755))
{
//$result = false;
if (is_file($source)) {
if ($dest[strlen($dest)-1]=='/') {
if (!file_exists($dest)) {
cmfcDirectory::makeAll($dest,$options['folderPermission'],true);
}
$__dest=$dest."/".basename($source);
} else {
$__dest=$dest;
}
$result = copy($source, $__dest);
chmod($__dest,$options['filePermission']);
} elseif(is_dir($source)) {
if ($dest[strlen($dest)-1]=='/') {
if ($source[strlen($source)-1]=='/') {
//Copy only contents
} else {
//Change parent itself and its contents
$dest=$dest.basename($source);
#mkdir($dest);
chmod($dest,$options['filePermission']);
}
} else {
if ($source[strlen($source)-1]=='/') {
//Copy parent directory with new name and all its content
#mkdir($dest,$options['folderPermission']);
chmod($dest,$options['filePermission']);
} else {
//Copy parent directory with new name and all its content
#mkdir($dest,$options['folderPermission']);
chmod($dest,$options['filePermission']);
}
}
$dirHandle=opendir($source);
while($file=readdir($dirHandle))
{
if($file!="." && $file!="..")
{
if(!is_dir($source."/".$file)) {
$__dest=$dest."/".$file;
} else {
$__dest=$dest."/".$file;
}
echo "$source/$file ||| $__dest<br />";
$result=smartCopy($source."/".$file, $__dest, $options);
}
}
closedir($dirHandle);
} else {
$result=false;
}
return $result;
}
//end of function
echo smartCopy('media', 'mobile/images');
function recurse_copy($src,$dst) {
$dir = opendir($src);
#mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
if(md5_file($src . '/' . $file) !== md5_file($dst . '/' . $file))
{
echo 'copying' . $src . '/' . $file; echo '<br/>';
copy($src . '/' . $file, $dst . '/' . $file);
}
}
}
}
closedir($dir);
}
If its on a Linux/Posix system then (depending on what access you have) it may be a lot simpler / faster to:
$chk=`rsync -qrRlpt --delete $src $dest`;
C.