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;
$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->user_login 的目录?如果存在,则继续下一个代码。

4

2 回答 2

4

http://nz.php.net/manual/en/function.move-uploaded-file.php#105026

目标目录必须存在;move_uploaded_file() 不会自动为您创建它。

只需使用is_dirmkdir

<?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";
}
?>
于 2012-08-04T14:54:27.053 回答
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 初始化之后添加带有 $uploaddir 参数的 if 语句is_dir()and mkdir()

于 2012-08-04T14:52:12.873 回答