2011-11-21 67 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 
相關問題