How can I move a file to another folder using php?

zeckdude picture zeckdude · Nov 21, 2011 · Viewed 37.1k times · Source

I have an upload form where users can upload images that are currently being uploaded to a folder I made called 'temp' and their locations are saved in an array called $_SESSION['uploaded_photos']. Once the user pushes the 'Next Page' button, I want it to move the files to a new folder that is dynamically created right before that.

if(isset($_POST['next_page'])) { 
  if (!is_dir('../images/uploads/listers/'.$_SESSION['loggedin_lister_id'])) {
    mkdir('../images/uploads/listers/'.$_SESSION['loggedin_lister_id']);
  }

  foreach($_SESSION['uploaded_photos'] as $key => $value) { 
    $target_path = '../images/uploads/listers/'.$_SESSION['loggedin_lister_id'].'/';
    $target_path = $target_path . basename($value); 

    if(move_uploaded_file($value, $target_path)) {
      echo "The file ".  basename($value). " has been uploaded<br />";
    } else{
      echo "There was an error uploading the file, please try again!";
    }

  } //end foreach

} //end if isset next_page

An example for a $value that is being used is:

../images/uploads/temp/IMG_0002.jpg

And an example of a $target_path that is being used is:

../images/uploads/listers/186/IMG_0002.jpg

I can see the file sitting in the temp folder, both of those paths look good to me and I checked to make sure that the mkdir function actually created the folder which it did well.

How can I move a file to another folder using php?

Answer

HorusKol picture HorusKol · Nov 21, 2011

As I read your scenario, it looks like you've handled the upload and moved the files to your 'temp' folder, and now you want to move the file when they perfom a new action (clicking on the Next button).

As far as PHP is concerned - the files in your 'temp' are not uploaded files anymore, so you can no longer use move_uploaded_file.

All you need to do is use rename:

if(isset($_POST['next_page'])) { 
  if (!is_dir('../images/uploads/listers/'.$_SESSION['loggedin_lister_id'])) {
    mkdir('../images/uploads/listers/'.$_SESSION['loggedin_lister_id']);
  }

  foreach($_SESSION['uploaded_photos'] as $key => $value) {
    $target_path = '../images/uploads/listers/'.$_SESSION['loggedin_lister_id'].'/';
    $target_path = $target_path . basename($value); 

    if(rename($value, $target_path)) {
      echo "The file ".  basename($value). " has been uploaded<br />";
    } else{
      echo "There was an error uploading the file, please try again!";
    }

  } //end foreach

} //end if isset next_page