如何使用 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
正在使用的 $value 的示例是:
../images/uploads/temp/IMG_0002.jpg
正在使用的 $target_path 的示例是:
../images/uploads/listers/186/IMG_0002.jpg
我可以看到该文件位于临时文件夹中,这两个路径对我来说看起来都不错,我检查以确保 mkdir 函数实际上创建了它所做的文件夹出色地。
如何使用 php 将文件移动到另一个文件夹?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当我阅读您的方案时,您似乎已经处理了上传并将文件移动到“临时”文件夹,现在您希望在文件执行新操作(单击“下一步”按钮)时移动文件。
就 PHP 而言 - “temp”中的文件不再是上传文件,因此您不能再使用 move_uploaded_file。
您需要做的就是使用重命名:
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: