PHP - Move a file into a different folder on the server
Asked Answered
P

10

235

I need to allow users on my website to delete their images off the server after they have uploaded them if they no longer want them. I was previously using the unlink function in PHP but have since been told that this can be quite risky and a security issue. (Previous code below:)

if(unlink($path.'image1.jpg')){ 
     // deleted
}

Instead i now want to simply move the file into a different folder. This must be able to be done a long time after they have first uploaded the file so any time they log into their account. If i have the main folder which stores the users image(s):

user/

and then within that a folder called del which is the destination to put their unwanted images:

user/del/

Is there a command to move a file into a different folder? So that say:

user/image1.jpg

moves to/becomes

user/del/image1.jpg
Pettus answered 2/10, 2013 at 14:28 Comment(0)
D
524

The rename function does this

docs rename

rename('image1.jpg', 'del/image1.jpg');

If you want to keep the existing file on the same place you should use copy

docs copy

copy('image1.jpg', 'del/image1.jpg');

If you want to move an uploaded file use the move_uploaded_file, although this is almost the same as rename this function also checks that the given file is a file that was uploaded via the POST, this prevents for example that a local file is moved

docs move_uploaded_file

$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        $name = $_FILES["pictures"]["name"][$key];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
    }
}

code snipet from docs

Denice answered 2/10, 2013 at 14:33 Comment(2)
One problem with rename() and copy() is you lost all the metadata such as created and modified date for example.. have that in mind.Volteface
The downside of rename() is that it doesn't actually moves the file as you expect. You'll need to use something like basename() or pathinfo() to retrieve the filename in order to store the file in the new directory with the same name.Ard
O
121

Use the rename() function.

rename("user/image1.jpg", "user/del/image1.jpg");
Ordination answered 2/10, 2013 at 14:32 Comment(0)
C
32

If you want to move the file in new path with keep original file name. use this:

$source_file = 'foo/image.jpg';
$destination_path = 'bar/';
rename($source_file, $destination_path . pathinfo($source_file, PATHINFO_BASENAME));
Canonry answered 24/1, 2018 at 16:38 Comment(2)
Worked like a charm.Paste
If you want to change the file name you can do it simply like this rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");Cosmetic
N
2

Some solution is first to copy() the file (as mentioned above) and when the destination file exists - unlink() file from previous localization. Additionally you can validate the MD5 checksum before unlinking to be sure

Nairobi answered 6/11, 2018 at 13:25 Comment(0)
A
2

I using shell read all data file then assign to array. Then i move file in top position.

i=0 
for file in /home/*.gz; do
    $file
    arr[i]=$file
    i=$((i+1)) 
done 
mv -f "${arr[0]}" /var/www/html/
Alurd answered 22/3, 2019 at 9:52 Comment(1)
Please explain that further - how could this work using PHP?Seppuku
E
2

Use file this code

function move_file($path,$to){
   if(copy($path, $to)){
      unlink($path);
      return true;
   } else {
     return false;
   }
 }
Eliott answered 17/1, 2021 at 18:3 Comment(1)
This should be the accepted answer, this to me is perfect. rename() is fine but it changes the file.Meshuga
I
1

Create a function to move it:

function move_file($file, $to){
    $path_parts = pathinfo($file);
    $newplace   = "$to/{$path_parts['basename']}";
    if(rename($file, $newplace))
        return $newplace;
    return null;
}
Ineffectual answered 19/3, 2019 at 16:49 Comment(0)
I
1
function xmove($src,$dst)
{

  if(is_dir($src)===true)
  { $dir=opendir($src);
    while (($file = readdir($dir)) !== false) {
        if ($file === '.' || $file === '..') {
            continue;
        }

        if (is_dir($src."/".$file) === true) {
            if (is_dir("$dst/$file") === false) {
                mkdir("$dst/$file");
            }
            //echo basename("$file")."<br>";
                xmove($src."/".$file,$dst."/".$file);
            
        }
        else {
            copy("$src/$file", "$dst/$file");
            unlink("$src/$file");
            
        }
    }

    closedir($dir);
    rmdir($src);
    return true;

  }else
  return false;

}
Isidraisidro answered 1/11, 2021 at 17:29 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Adjuvant
D
0

use copy() and unlink() function

$moveFile="path/filename";
if (copy($csvFile,$moveFile)) 
{
  unlink($csvFile);
}
Davy answered 20/3, 2019 at 10:0 Comment(0)
S
-4

shell_exec('mv filename dest_filename');

Selfless answered 21/9, 2018 at 6:28 Comment(1)
Welcome to Stack Overflow! While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations!Kepner

© 2022 - 2024 — McMap. All rights reserved.