我有以下代码上传文件:
<?php
//set the image size in mb
$max_upload_size='10';
$MAXIMUM_FILESIZE = $max_upload_size * 1024 * 1024;
get_current_user();
global $current_user;
$uploaddir = './uploads/file/'.$current_user->user_login.'/';
$file = $uploaddir . basename($_FILES['uploadfile']['name']);
if ($_FILES['uploadfile']['size']<$MAXIMUM_FILESIZE) {
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
echo "success";
} else {
echo "error";
}
}else{
echo"size_error";
}
?>
如果user_login已存在于/ uploads / file /目录下,则此方法很有用。如果不存在,我如何创建基于变量$ current_user-&gt; user_login的目录?如果存在,则继续下一个代码。
答案 0 :(得分:3)
来自http://nz.php.net/manual/en/function.move-uploaded-file.php#105026:
目标目录必须存在; move_uploaded_file()不会自动为你创建它。
<?php
//set the image size in mb
$max_upload_size='10';
$MAXIMUM_FILESIZE = $max_upload_size * 1024 * 1024;
global $current_user;
$current_user = get_current_user();
$uploaddir = './uploads/file/'.$current_user->user_login.'/';
if (!is_dir($uploaddir) && !mkdir($uploaddir)){
die("Error creating folder $uploaddir");
}
$file = $uploaddir . basename($_FILES['uploadfile']['name']);
if ($_FILES['uploadfile']['size']<$MAXIMUM_FILESIZE) {
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
echo "success";
} else {
echo "error";
}
}else{
echo"size_error";
}
?>
答案 1 :(得分:1)
<?php
//set the image size in mb
$max_upload_size='10';
$MAXIMUM_FILESIZE = $max_upload_size * 1024 * 1024;
get_current_user();
global $current_user;
if(!is_dir('./uploads/file/'.$current_user->user_login))
{
mkdir('./uploads/file/'.$current_user->user_login);
}
$uploaddir = './uploads/file/'.$current_user->user_login.'/';
$file = $uploaddir . basename($_FILES['uploadfile']['name']);
if ($_FILES['uploadfile']['size']<$MAXIMUM_FILESIZE) {
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
echo "success";
} else {
echo "error";
}
}else{
echo"size_error";
}
?>
或者在$ updloaddir初始化之后,在is_dir()
和mkdir()
中添加带有$ uploaddir参数的if语句。