如何在使用 move_uploaded_file() 时在 PHP 中创建目标(文件夹)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4384951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create destination (Folder) in PHP while using move_uploaded_file()?
提问by alex
I want to upload files with PHP and i use move_uplload_files to copy them to the destination folder I want, everything works fine with this :
我想用 PHP 上传文件,我使用 move_uplload_files 将它们复制到我想要的目标文件夹,一切正常:
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], './uploades/'))
die("success");
else
die("error");
But when I try this
但是当我尝试这个时
$rand = chr(rand(97, 122)). chr(rand(97, 122)). chr(rand(97, 122));
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], './uploades/'.$rand))
die("success");
else
die("error");
I will get error, and it looks like move_uploaded_files can notcreate folders. How can I do this ?
我会收到错误消息,看起来 move_uploaded_files无法创建文件夹。我怎样才能做到这一点 ?
Basically I am looking for a way to do it like file_put_contents()
that creates the path if not exist.
基本上我正在寻找一种方法来做到这一点file_put_contents()
,如果不存在就创建路径。
回答by alex
回答by Vikash
回答by Shakti Singh
Create the directory first using mkdir()
首先使用创建目录 mkdir()
$rand = chr(rand(97, 122)). chr(rand(97, 122)). chr(rand(97, 122));
mkdir('./uploades/'.$rand);
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], './uploades/'.$rand))
die("success");
else
die("error");
回答by Cees Timmerman
This works for me:
这对我有用:
$path = "upload/";
$name = $_FILES["file"]["name"];
// Remove dangerous characters from filename.
$name = str_replace('..', '', $name);
$name = str_replace('/', '', $name);
$name = str_replace('\', '', $name);
if (($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
&& ($_FILES["file"]["size"] < 2000000)) {
if ($_FILES["file"]["error"] > 0) {
echo "Error " . $_FILES["file"]["error"] . "<br>";
} else {
if(file_exists($path.$name)){
echo "$path$name already exists. ";
} else {
@mkdir($path, 0666, true); // Create non-executable upload folder(s) if needed.
move_uploaded_file($_FILES["file"]["tmp_name"], $path.$name);
echo "Stored in: $path$name";
}
}
} else {
echo "Invalid file. Allowed are JPG smaller than 2 MB.";
}
回答by Aryan
if($_FILES['file_up']['type']=='image/jpeg' || $_FILES['file_up']['type']=='image/png' || $_FILES['file_up']['type']=='image/gif')
{
move_uploaded_file($_FILES['file_up']['tmp_name'],'uploads/'.time().$_FILES['file_up']['name']);
}
else
{
echo "Upload only image file..";
}