2011-11-21 101 views
11

我有一个上传表单,用户可以上传当前正在上传到我称为'temp'的文件夹的图像,并将它们的位置保存在名为$ _SESSION ['uploaded_photos']的数组中。一旦用户按下“下一页”按钮,我希望它将文件移动到在此之前动态创建的新文件夹。如何使用php将文件移动到另一个文件夹?

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 

为正在使用一个$值的一个例子是:

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

而一个$ target_path的一个例子正在使用的是:

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

我可以看到坐在临时文件夹中的文件,这两个路径对我来说都很好,我检查确认mkdir函数实际上创建了它的文件夹。

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

回答

20

当我阅读你的场景时,它看起来像你已经处理了上传并将文件移动到了你的“临时”文件夹,现在你想在文件执行新动作时移动文件(点击下一步按钮)。

就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 
相关问题