Home > Net >  Move Files with specific extentions from a directory to a subdirectory in PHP
Move Files with specific extentions from a directory to a subdirectory in PHP

Time:04-12

This question has probably been asked before but I can't find the solution in the previously suggested solutions. I am fairly new to PHP and I'm trying to move files with the extention .zip to a subfolder. After I loop through the source folder to find the specific files, I can't use the rename() method to move the files to the subfolder.

<?php
$updatesFolder = realpath('C:\xampp\htdocs\project\updates');
$archiveFolder = realpath('C:\xampp\htdocs\project\updates\archive');
if (file_exists($updatesFolder) && is_dir($updatesFolder)) {         
    // Get the files of the directory as an array
    $scan_arr = scandir($updatesFolder);
    $files_arr = array_diff($scan_arr, array('.','..') );
    //echo "<pre>"; print_r( $files_arr ); echo "</pre>";
    // Get each files of directory with line break
    foreach ($files_arr as $file) {
        //Get the file path
        $file_path = $updatesFolder.$file;
        //echo $file_path;
        // Get the file extension
        $file_ext = pathinfo($file_path, PATHINFO_EXTENSION);
        if ($file_ext=="zip") {
            $data = $file;
            $dirHandle = opendir($updatesFolder);
            $dirHandle2 = opendir($archiveFolder);
            while ($file = readdir($dirHandle)) {
                if ($file==$data) {
                    //unlink($updatesFolder.'/'.$file);
                    //var_dump ($data);
                    rename($updatesFolder , $archiveFolder); 
                }          
            }
        }                
    }   
} else {
    echo "Directory does not exists";
}
?>

CodePudding user response:

There is quite a bit of unnecessary code in there, I assume from multiple tries at fixing it.

Basically the main problem is you must move one file at a time, by name

$updatesFolder = realpath('./database');
$archiveFolder  = realpath('./database/archive');
echo $updatesFolder . PHP_EOL . $archiveFolder . PHP_EOL;
if (file_exists($updatesFolder) && is_dir($updatesFolder)) {         
    
    $scan_arr = scandir($updatesFolder);
    $files_arr = array_diff($scan_arr, array('.','..') );
    
    foreach ($files_arr as $file) {

        if ("zip" == pathinfo($file, PATHINFO_EXTENSION)) {

            rename($updatesFolder.'/'.$file , $archiveFolder.'/'.$file);
        }                
    }   
} else {
    echo "Directory does not exists";
}
  • Related