【问题标题】:Create upload path based on current year and month根据当前年份和月份创建上传路径
【发布时间】:2023-11-07 11:35:01
【问题描述】:

为了上传,我想检查年文件夹和月子文件夹是否已经存在。如果他们不这样做,我想创建它们并将我的上传保存在那里。

<?php
     $newname =  $_POST['changename'];
      $temp = explode(".", $_FILES["uploadfile"]["name"]);
        $extension = end($temp);

        if(!(
        $_FILES['uploadfile']['type']=='image/jpeg' ||
        $_FILES['uploadfile']['type']=='image/png' ||
        $_FILES['uploadfile']['type']=='image/gif' ||
        $_FILES['uploadfile']['type']=='image/bmp' 
        )) // if file does not equal these types, kill it
        {
        echo  $_FILES['uploadfile']['type'] . " is not an acceptable format.";
        die();
        }

        if ($_FILES["uploadfile"]["size"] > 20000000)
            {
                echo "File too big. Max 20mb";
                die();
            }

        if ($_FILES["uploadfile"]["error"] > 0)
            {
            echo "Return Code: " . $_FILES["uploadfile"]["error"] . "<br>";
            }
          else
            {
                $new_file_name = $newname.".".$extension;
                $path = "uploads/".$new_file_name;
                move_uploaded_file($_FILES["uploadfile"]["tmp_name"],$path);
                echo json_encode(array(
                    "success" => true,
                    "imagepath" => $path,
                    "filetype" => $_FILES["uploadfile"]["type"],
                    "new_file_name" => $newname,
                    "fileName" => $_FILES["uploadfile"]["name"],
                    "fileTmp" => $_FILES["uploadfile"]["tmp_name"],                     
                ));
            }
 ?>

【问题讨论】:

  • 已授予权限...继续编写代码,如果遇到错误,请返回...
  • 你可以使用 is_dir() 函数。
  • 您应该确定要在您的文件夹系统中使用哪种格式的年份和月份...我的意思是您要创建四位数或两位数的年份目录
  • 我用我当前的代码编辑了我的问题。

标签: php mkdir uploading


【解决方案1】:

用这样的东西去:

$year = date("Y");   
$month = date("m");   
$filename = "../".$year;   
$filename2 = "../".$year."/".$month;

if(file_exists($filename)){
    if(file_exists($filename2)==false){
        mkdir($filename2,0777);
    }
}else{
    mkdir($filename,0777);
}

您必须根据您拥有的目录结构调整此代码。它向您展示了检查文件或目录是否存在的基本思想,如果不存在,那么它将由您创建。

编辑 1:

根据您的需要调整您的代码,应该是这样的(未经测试):

$path = "uploads/";

$year_folder = $path . date("Y");
$month_folder = $year_folder . '/' . date("m");

!file_exists($year_folder) && mkdir($year_folder , 0777);
!file_exists($month_folder) && mkdir($month_folder, 0777);

$path = $month_folder . '/' . $new_file_name;

注意:放在上面

move_uploaded_file($_FILES["uploadfile"]["tmp_name"],$path);

【讨论】:

  • 你只是复制/粘贴它?如果您只需要有效的解决方案,我需要的不仅仅是您的问题!
  • 请问0777是什么意思?这是干什么用的?
  • 这是一个UNIX文件权限,777表示所有者、组和每个人的读+写+执行。权限号应为八进制(前缀为0)
  • 感谢您的解释!我真的不知道 mkdir 是如何工作的。我用我的代码编辑了我的问题。你能帮帮我吗?
  • 我相信这个答案很好。也许(如果我理解正确的话)else 分支中缺少月份 mkdir,但在其他方面很有用。
【解决方案2】:

is_dir 应该用于检查目录/文件夹的存在,而不是file_exists,如果找到具有该文件名的文件,file_exists 也将返回 true。 有一个递归参数,当设置为 true 时,将生成所有嵌套目录。 例如

    $pathname_parameter = date("Y") . '/' . date("m") . '/';
    $mode_parameter = 0777;
    $recursive_parameter = true; 

    if (!is_dir($pathname_parameter)) {
        mkdir($pathname_parameter, $mode_parameter, $recursive_parameter);
    }

所以你的会是这样的

    $new_file_name = $newname.".".$extension;
    $pathname = 'uploads/' . date("Y") . '/' . date("m") . '/';

    if (!is_dir($pathname)) {
        mkdir($pathname, 0777, true);
    }
    $destination = $pathname . $new_file_name;  
    /* if( (!is_file($destination)) || (isset($_POST['overwrite']) && (int)$_POST['overwrite']) ){ */
    move_uploaded_file($_FILES["uploadfile"]["tmp_name"], $destination);    
   /* } */

【讨论】:

  • @jekeyeke 感谢您的编辑建议,即使您的编辑被拒绝,我也更改了答案。
  • $pathname 应该以正斜杠结尾,否则会将文件放在年份目录中
【解决方案3】:
if (!file_exists(date("Y")))//Checking if year folder exist
    mkdir(date("Y"));//Creating folder if it dosent exist(You may need to add ,0777) in UNIX
if (!file_exists(date("Y").'/'.date("m")))//Checking for month folder
    mkdir(date("Y").'/'.date("m"));
$path='./'.date("Y/m").'/';

【讨论】:

    【解决方案4】:

    第一个参数路径示例“assets/upload”第二个参数允许文件“option NUll”第三个参数文件名示例“image.png”返回文件名

    public function upload_file_date_directory($paths,$allow = '', $file) {
    
       $year = date('Y');
       $month = date('m');
       $path = "./". $paths . $year . "/" . $month;
       if (!is_dir($path)) {
            mkdir($path, 0777, true);
       }
    
       $config['upload_path'] = $path;
       $config['allowed_types'] = "gif|jpg|png|jpeg|$allow";
       $config['max_size'] = '3000';
       $config['max_width'] = '2000';
       $config['max_height'] = '2000';
       $config['file_name'] = trim(str_replace(" ", "", date('dmYHis')));
       $this->load->library('upload', $config);
    
       $newimg = '';
       if (!$this->upload->do_upload($file)) {
            $error = array('error' => $this->upload->display_errors());
            $newimg = $error;
            return $newimg;
       } else {
            $data = array('upload_data' => $this->upload->data());
            $newimg = $data['upload_data']['file_name'];
            return  $year . "/" . $month ."/".$newimg;
       }
    
    }
    

    【讨论】: