PHP - 将文件移动到服务器上的不同文件夹中
我需要允许我网站上的用户在上传图片后从服务器上删除他们不再需要的图片.我以前在 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
文档 move_uploaded_file
$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");
}
}
来自文档的代码片段
相关文章