我想用PHP上传文件,我使用move_uplload_files将它们复制到我想要的目标文件夹,一切正常如下:
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], './uploades/'))
die("success");
else
die("error");
但是当我尝试这个时
$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");
我会收到错误,看起来像move_uploaded_files 无法创建文件夹。我怎么能这样做?
基本上我正在寻找一种方法来像file_put_contents()
那样创建路径(如果不存在)。
答案 0 :(得分:30)
使用mkdir()
。
如果您需要制作多个文件夹,例如传递a/b/c
,请将第三个参数设置为TRUE
。
你可以测试它是否已经存在,如果不是这样的话就添加....
$path = 'abc';
if ( ! is_dir($path)) {
mkdir($path);
}
答案 1 :(得分:5)
答案 2 :(得分:1)
首先使用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");
答案 3 :(得分:1)
这对我有用:
$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.";
}
答案 4 :(得分:-2)
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..";
}