Shreya
Shreya

Reputation: 71

How to move files to another folder in php

I have 4 csv files in "files" folder & I want to move these files with content to another folder (i.e. backups),Files are given below.

  1. abc.csv
  2. abc1.csv
  3. abc2.csv

$files = scandir('files');
$destination = 'backups/';
$date = date('Y-m-d');
foreach($files as $file){
    $rename_file = $file.'_'.$date;
    move_uploaded_file($rename_file, "$destination");
}

Upvotes: 4

Views: 17205

Answers (2)

JustBaron
JustBaron

Reputation: 2347

Since you are not uploading any files, try rename() function instead.

$Ignore = array(".","..","Thumbs.db");
$OriginalFileRoot = "files";
$OriginalFiles = scandir($OriginalFileRoot);
$DestinationRoot = "backups";
# Check to see if "backups" exists
if(!is_dir($DestinationRoot)){
    mkdir($DestinationRoot,0777,true);
}
$Date = date('Y-m-d');
foreach($OriginalFiles as $OriginalFile){
    if(!in_array($OriginalFile,$Ignore)){
        $FileExt = pathinfo($OriginalFileRoot."\\".$OriginalFile, PATHINFO_EXTENSION); // Get the file extension
        $Filename = basename($OriginalFile, ".".$FileExt); // Get the filename
        $DestinationFile = $DestinationRoot."\\".$Filename.'_'.$Date.".".$FileExt; // Create the destination filename 
        rename($OriginalFileRoot."\\".$OriginalFile, $DestinationFile); // rename the file            
    }
}

Upvotes: 8

Dekel
Dekel

Reputation: 62556

The function move_uploaded_file is relevant for uploading files, not for other things.

To move file in the filesystem you should use the rename function:

$files = scandir('files');
$destination = 'backups/';
$date = date('Y-m-d');
foreach($files as $file){
    if (!is_file($file)) {
        continue;
    }
    $rename_file = $destination.$file.'_'.$date;
    rename($file, $rename_file);
}

Upvotes: 3

Related Questions