我想动态地为图像创建新的文件夹,当一个目录中有1000个图像时。使用PHP、MySQL,实现这种事情的最佳实践是什么?:)感谢
要计算文件夹中的文件数,请参考以下答案。
然后使用mkdir()函数创建一个新目录。
所以你会有这样的东西:
$directory = 'images';
$files = glob($directory . '*.jpg');
if ( $files !== false )
{
$filecount = count( $files );
if ($filecount >= 1000)
{
mkdir('images_2');
}
}
从这个例子中计算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
?>
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 );
}
我在我的网站上使用这些代码,仅供参考
所以我这样解决了我的问题。
我使用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');
}
您可以尝试类似的东西
$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
}
}