PHP在文件夹中的数千个图像后动态创建新文件夹

时间:2014-10-28 11:02:11

标签: php file upload max directory

我想动态创建图像的新文件夹,当一个目录中有1000个图像时使用PHP,MySQL什么是实现这种事情的最佳实践? :)谢谢

5 个答案:

答案 0 :(得分:0)

要计算文件夹中的文件数,我建议您使用answer

然后,您将使用mkdir()函数创建新目录。

所以你会有类似的东西:

$directory = 'images';
$files = glob($directory . '*.jpg');

if ( $files !== false )
{
    $filecount = count( $files );
    if ($filecount >= 1000)
    {
        mkdir('images_2');
    }
}

答案 1 :(得分:0)

从此示例中Count how many files in directory php

添加if语句,该语句将在文件达到特定数量时创建文件夹

<?php 
$dir = opendir('uploads/'); # This is the directory it will count from
$i = 0; # Integer starts at 0 before counting

# While false is not equal to the filedirectory
while (false !== ($file = readdir($dir))) { 
    if (!in_array($file, array('.', '..') and !is_dir($file)) $i++;
    if($i == 1000) mkdir('another_folder');
}

echo "There were $i files"; # Prints out how many were in the directory

&GT;

答案 2 :(得分:0)

你可以尝试这样的事情

$dir = "my_img_folder/";

if(is_dir($dir)) {
    $images = glob("$dir{*.gif,*.jpg,*.JPG,*.png}", GLOB_BRACE); //you can add .gif or other extension as well

    if(count($images) == 1000){
        mkdir("/path/to/my/dir", 0777); //make the permission as per your requirement
    }
}

答案 3 :(得分:0)

define("IMAGE_ROOT","/images");

function getLastFolderID(){

    $directory = array_diff( scandir( IMAGE_ROOT ), array(".", "..") );

    //if there is empty root, return zero. Else, return last folder name;
    $id = empty($directory) ? 0 : intval( end($directory) );

    return $id;
}

$last_dir = getLastFolderID();

$target_path = IMAGE_ROOT . DIRECTORY_SEPARATOR . $last_dir;

$file_count = count( array_diff( scandir( $target_path ), array(".", "..") ) ); // exclude "." and ".."

//large than 1000 or there is no folder
if( $file_count > 1000 || $last_dir == 0){

    $new_name = getLastFolderID() + 1;
    $new_dir = IMAGE_ROOT . DIRECTORY_SEPARATOR . $new_name;

    if( !is_dir($new_dir) )
        mkdir( $new_dir );

}

我在我的网站上使用这些代码,FYR

答案 4 :(得分:0)

所以我解决了这个问题。

我正在使用laravel进行php开发。

首先我要获取最后一个图片文件夹,然后检查是否有超过1000张图片。

如果是的话我正在创建具有当前日期时间的新文件夹。

代码看起来像这样。

// get last image  
$last_image = DB::table('funs')->select('file')
                               ->where('file', 'LIKE', 'image%')
                               ->orderBy('created_at', 'desc')->first();

// get last image directory                            
$last_image_path = explode('/', $last_image->file);

// last directory
$last_directory = $last_image_path[1];

$fi = new FilesystemIterator(public_path('image/'.$last_directory),  FilesystemIterator::SKIP_DOTS);

if(iterator_count($fi) > 1000){
   mkdir(public_path('image/fun-'.date('Y-m-d')), 0777, true);
   $last_directory = 'fun-'.date('Y-m-d');
}