如何使用php将文件移动到另一个文件夹


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

我有一个上传表单,用户可以上传图像,目前正在被上传到一个文件夹,我叫'temp'和他们的位置被保存在一个名为$_SESSION['uploaded_photos']数组。一旦用户按下"下一页"按钮,我希望它将文件移动到在此之前动态创建的新文件夹中。

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

使用$值的一个例子是:

. ./图片/上传/temp/IMG_0002.jpg

使用$target_path的一个例子是:

. ./图片/上传/富人/186/IMG_0002.jpg

我可以看到文件位于临时文件夹中,这两个路径对我来说都很好,我检查了mkdir函数是否确实创建了它所做的文件夹。

如何使用php将文件移动到另一个文件夹?

当我阅读您的场景时,看起来您已经处理了上传并将文件移动到您的'temp'文件夹,现在您想在执行新操作(单击Next按钮)时移动文件。

就PHP而言- 'temp'中的文件不再是上传文件,因此您不能再使用move_uploaded_file。

你需要做的就是使用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