PHP-将文件移至服务器上的其他文件夹 [英] PHP - Move a file into a different folder on the server
问题描述
我需要允许我网站上的用户在不再需要上传后将其图像从服务器上删除.我以前在PHP中使用unlink
函数,但此后被告知这可能存在很大的风险和安全性问题. (下面的先前代码:)
I need to allow users on my website to delete their images off the server after they have uploaded them if they no longer want them. I was previously using the unlink
function in PHP but have since been told that this can be quite risky and a security issue. (Previous code below:)
if(unlink($path.'image1.jpg')){
// deleted
}
现在我只想简单地将文件移到另一个文件夹中.他们必须在首次上传文件后很长一段时间才能完成此操作,因此他们可以随时登录自己的帐户.如果我有用于存储用户图像的主文件夹:
Instead i now want to simply move the file into a different folder. This must be able to be done a long time after they have first uploaded the file so any time they log into their account. If i have the main folder which stores the users image(s):
user/
,然后在名为del的文件夹中,该文件夹是放置不需要的图像的目的地:
and then within that a folder called del which is the destination to put their unwanted images:
user/del/
是否有将文件移动到其他文件夹的命令?这样说:
Is there a command to move a file into a different folder? So that say:
user/image1.jpg
移至/成为
user/del/image1.jpg
推荐答案
rename
函数执行此操作
rename('image1.jpg', 'del/image1.jpg');
如果要将现有文件保存在同一位置,则应使用copy
If you want to keep the existing file on the same place you should use copy
copy('image1.jpg', 'del/image1.jpg');
如果要移动上载的文件,请使用move_uploaded_file
,尽管它与rename
几乎相同,但此功能还会检查给定的文件是否是通过POST
上载的文件,这可以防止本地文件被移动的示例
If you want to move an uploaded file use the move_uploaded_file
, although this is almost the same as rename
this function also checks that the given file is a file that was uploaded via the POST
, this prevents for example that a local file is moved
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
文档中的代码段
这篇关于PHP-将文件移至服务器上的其他文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!