I write this element, but when I want to display the directory in dropown, I have the same directory twice.
LMy first dropdown work well:
blog
image
My second dropdown write the directory twice
blog
image
blog
image
<?php
//function
function osc_opendir($path) {
$path = rtrim($path, '/') . '/';
$exclude_array = array('.', '..', '.DS_Store', '.directory', '.htaccess', 'Thumbs.db','.php', '_note');
$result = array();
if ($handle = opendir($path)) {
while (false !== ($filename = readdir($handle))) {
if (!in_array($filename, $exclude_array)) {
$file = array('name' => $path . $filename,
'is_dir' => is_dir($path . $filename),
'writable' => is_writable($path . $filename)
);
$result[] = $file;
if ($file['is_dir'] == true) {
$result = array_merge($result, osc_opendir($path . $filename));
}
}
}
closedir($handle);
}
return $result;
// place allowed sub-dirs in array, non-recursive
// just only one image
$dir_array = array();
foreach (osc_opendir($root_images_dir) as $file) {
if ($file['is_dir']) {
$img_dir_products_image = substr($file['name'], strlen($root_images_dir));
$drop_array[] = array('id' => $img_dir_products_image,
'text' => $img_dir_products_image
);
}
}
echo HTML::selectMenu('directory_products_image', $drop_array);
// second dropdown
// for the image gallery
// gallery
// lecture des fichiers
$dir_array = array();
foreach (osc_opendir($root_images_dir) as $file1) {
if ($file1['is_dir']) {
$img_dir = substr($file1['name'], strlen($root_images_dir));
$drop_array[] = array('id' => $img_dir,
'text' => $img_dir
);
}
}
echo '<div class="row"><span class="col-xs-3">'.TEXT_PRODUCTS_IMAGE_DIRECTORY. ' ' . HTML::selectMenu('directory', $drop_array) . '</span></div>';
echo TEXT_PRODUCTS_IMAGE_NEW_FOLDER_GALLERY . HTML::inputField('new_directory','','class="input-small"') .'<br /><br />';
You're getting it twice, because you're ADDING it twice:
$result[] = $file;
^^---append filename to array
$result = array_merge($result, osc_opendir($path . $filename));
^^^^^^^--- add it yet again
Related
I have the next code but i need scan multiple dir on array.
public static function scanFiles($directory, $recursive = true, $listDirs = false, $listFiles = true, $exclude = '') {
$arrayItems = array();
$skipByExclude = false;
$handle = opendir($directory);
if ($handle) {
while (false !== ($file = readdir($handle))) {
preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE|\.html))$/iu", $file, $skip);
if($exclude){
preg_match($exclude, $file, $skipByExclude);
}
if (!$skip && !$skipByExclude) {
if (is_dir($directory. DS . $file)) {
if($recursive) {
$arrayItems = array_merge($arrayItems, self::scanFiles($directory. DS . $file, $recursive, $listDirs, $listFiles, $exclude));
}
if($listDirs){
$file = $directory . DS . $file;
$arrayItems[] = $file;
}
} else {
if($listFiles){
$file = $directory . DS . $file;
$arrayItems[] = $file;
}
}
}
}
closedir($handle);
}
return $arrayItems;
}
Your use is: scanFiles('path/to/folder')
But I need the path to be an array, example: scanFiles(array('path/to/folder1', 'path/to/folder2')).
Some one help...?
Thank you in advance and sorry for my bad english.
you can change the function like this, just adding foreach with the code block that you have for scanning directory
public static function scanFiles($directories, $recursive = true, $listDirs = false, $listFiles = true, $exclude = '') {
$arrayItems = array();
$skipByExclude = false;
foreach($directories as $directory) {
$handle = opendir($directory);
if ($handle) {
while (false !== ($file = readdir($handle))) {
preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE|\.html))$/iu", $file, $skip);
if ($exclude){
preg_match($exclude, $file, $skipByExclude);
}
if (!$skip && !$skipByExclude) {
if (is_dir($directory. DS . $file)) {
if ($recursive) {
$arrayItems = array_merge($arrayItems, self::scanFiles($directory. DS . $file, $recursive, $listDirs, $listFiles, $exclude));
}
if ($listDirs) {
$file = $directory . DS . $file;
$arrayItems[] = $file;
}
} else {
if ($listFiles) {
$file = $directory . DS . $file;
$arrayItems[] = $file;
}
}
}
}
closedir($handle);
}
}
return $arrayItems;
}
Well i am trying to edit this code to include all sub-folders, the problem is this code only search images into 1 folder, it will not search images into sub-folders.
Header("content-type: application/x-javascript");
$pathstring=pathinfo($_SERVER['PHP_SELF']);
$locationstring="http://" . $_SERVER['HTTP_HOST'].$pathstring['dirname'] . "/";
function returnimages($dirname=".")
{
$pattern="~\.(jpe?g|gif)$~";
$files = array();
if($handle = opendir($dirname))
{
while(false !== ($file = readdir($handle))){
if(preg_match($pattern, $file)){
$files[] = $file;
}
}
closedir($handle);
}
// sort pics in reverse order
rsort($files);
// output images into javascript array
foreach($files as $key => $pic)
{
echo "picsarray[$key] = '$pic';";
}
}
echo 'var locationstring="' . $locationstring . '";';
echo 'var picsarray=new Array();';
returnimages();
The idea can someone fix this code to be able to search all images including the sub-folders.
I hope this approach is useful to you:
Header("content-type: application/x-javascript");
$pathstring=pathinfo($_SERVER['PHP_SELF']);
$locationstring="http://" . $_SERVER['HTTP_HOST'].$pathstring['dirname'] . "/";
function returnImages($dir = ".")
{
$files = array_diff(scandir($dir), Array(".", ".."));
$dir_array = Array();
$images = array();
$pattern="~\.(jpe?g|gif)$~";
foreach ($files as $file) {
$path = $dir . "/" . $file;
if (is_dir($path)) {
// This does the magic, if is a folder, we recursively seek for more images.
$images = array_merge($images, returnImages($path));
}
else if (preg_match($pattern, $path)) {
$images[] = $path;
}
}
return $images;
}
function printSortedImages(array $images) {
// sort pics in reverse order
rsort($images);
// output images into javascript array
foreach($images as $key => $pic)
{
echo "picsarray[$key] = '$pic';";
}
}
echo 'var locationstring="' . $locationstring . '";';
echo 'var picsarray=new Array();';
$images = returnImages();
printSortedImages($images);
Hy all,
I'm working on an import of more than 30.000 products from an old webshop system to my OpenCart application.
I've got the categories working, and the products, but there is only 1 thing that i can't fix. That is that there's no image.
I've uploaded all images in OpenCartRoot/image/data/old/tt_productsv2/images/
In the database, it is inserted:
image/old/tt_productsv2/images/greatest.jpg
I've confirmed that that image exist, but when i check the front-end page, there are no images. Also when i check the back-end, i don't see any image linked to the product.
So my question is, what wrong I have done? Why isn't the image linked to the product, although i inserted the link in the database...
The path to the image in the database should only be
old/tt_productsv2/images/greatest.jpg
as OpenCart will build the path like
DIR_IMAGE . 'old/tt_productsv2/images/greatest.jpg'
where DIR_IMAGE is defined like
define('DIR_IMAGE', '/path/to/web/root/image/');
Yes, this is a problem with GLOBAL_BRACE Constant.
Some servers do not support that constant value, so you can change the
server or change the code.
The code is in:
admin / controller / common/ filemanager.php
line No : 37 ===================================================================
<?php
class ControllerCommonFileManager extends Controller {
public function index() {
$this->load->language('common/filemanager');
if (isset($this->request->get['filter_name'])) {
$filter_name = rtrim(str_replace(array('../', '..\\', '..', '*'), '', $this->request->get['filter_name']), '/');
} else {
$filter_name = null;
}
// Make sure we have the correct directory
if (isset($this->request->get['directory'])) {
$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
} else {
$directory = DIR_IMAGE . 'catalog';
}
if (isset($this->request->get['page'])) {
$page = $this->request->get['page'];
} else {
$page = 1;
}
$data['images'] = array();
$this->load->model('tool/image');
// Get directories
$directories = glob($directory . '/' . $filter_name . '*', GLOB_ONLYDIR);
if (!$directories) {
$directories = array();
}
// Get files
// $files = glob($directory . '/' . $filter_name . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
$files1 = glob($directory . '/' . $filter_name . '*.jpg');
if (!$files1) {
$files1 = array();
}
$files2 = glob($directory . '/' . $filter_name . '*.jpeg');
if (!$files2) {
$files2 = array();
}
$files3 = glob($directory . '/' . $filter_name . '*.JPG');
if (!$files3) {
$files3 = array();
}
$files4 = glob($directory . '/' . $filter_name . '*.png');
if (!$files4) {
$files4 = array();
}
$files5 = glob($directory . '/' . $filter_name . '*.JPEG');
if (!$files5) {
$files5 = array();
}
$files6 = glob($directory . '/' . $filter_name . '*.PNG');
if (!$files6) {
$files6 = array();
}
$files7 = glob($directory . '/' . $filter_name . '*.GIF');
if (!$files7) {
$files7 = array();
}
$files8 = glob($directory . '/' . $filter_name . '*.gif');
if (!$files8) {
$files8 = array();
}
$files = array_merge($files1, $files2,$files3,$files4,$files5,$files6,$files7,$files8);
// Merge directories and files
$images = array_merge($directories, $files);
// Get total number of files and directories
$image_total = count($images);
// Split the array based on current page number and max number of items per page of 10
$images = array_splice($images, ($page - 1) * 16, 16);
foreach ($images as $image) {
$name = str_split(basename($image), 14);
if (is_dir($image)) {
$url = '';
if (isset($this->request->get['target'])) {
$url .= '&target=' . $this->request->get['target'];
}
if (isset($this->request->get['thumb'])) {
$url .= '&thumb=' . $this->request->get['thumb'];
}
$data['images'][] = array(
'thumb' => '',
'name' => implode(' ', $name),
'type' => 'directory',
'path' => utf8_substr($image, utf8_strlen(DIR_IMAGE)),
'href' => $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . '&directory=' . urlencode(utf8_substr($image, utf8_strlen(DIR_IMAGE . 'catalog/'))) . $url, true)
);
} elseif (is_file($image)) {
// Find which protocol to use to pass the full image link back
if ($this->request->server['HTTPS']) {
$server = HTTPS_CATALOG;
} else {
$server = HTTP_CATALOG;
}
$data['images'][] = array(
'thumb' => $this->model_tool_image->resize(utf8_substr($image, utf8_strlen(DIR_IMAGE)), 100, 100),
'name' => implode(' ', $name),
'type' => 'image',
'path' => utf8_substr($image, utf8_strlen(DIR_IMAGE)),
'href' => $server . 'image/' . utf8_substr($image, utf8_strlen(DIR_IMAGE))
);
}
}
$data['heading_title'] = $this->language->get('heading_title');
$data['text_no_results'] = $this->language->get('text_no_results');
$data['text_confirm'] = $this->language->get('text_confirm');
$data['entry_search'] = $this->language->get('entry_search');
$data['entry_folder'] = $this->language->get('entry_folder');
$data['button_parent'] = $this->language->get('button_parent');
$data['button_refresh'] = $this->language->get('button_refresh');
$data['button_upload'] = $this->language->get('button_upload');
$data['button_folder'] = $this->language->get('button_folder');
$data['button_delete'] = $this->language->get('button_delete');
$data['button_search'] = $this->language->get('button_search');
$data['token'] = $this->session->data['token'];
if (isset($this->request->get['directory'])) {
$data['directory'] = urlencode($this->request->get['directory']);
} else {
$data['directory'] = '';
}
if (isset($this->request->get['filter_name'])) {
$data['filter_name'] = $this->request->get['filter_name'];
} else {
$data['filter_name'] = '';
}
// Return the target ID for the file manager to set the value
if (isset($this->request->get['target'])) {
$data['target'] = $this->request->get['target'];
} else {
$data['target'] = '';
}
// Return the thumbnail for the file manager to show a thumbnail
if (isset($this->request->get['thumb'])) {
$data['thumb'] = $this->request->get['thumb'];
} else {
$data['thumb'] = '';
}
// Parent
$url = '';
if (isset($this->request->get['directory'])) {
$pos = strrpos($this->request->get['directory'], '/');
if ($pos) {
$url .= '&directory=' . urlencode(substr($this->request->get['directory'], 0, $pos));
}
}
if (isset($this->request->get['target'])) {
$url .= '&target=' . $this->request->get['target'];
}
if (isset($this->request->get['thumb'])) {
$url .= '&thumb=' . $this->request->get['thumb'];
}
$data['parent'] = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url, true);
// Refresh
$url = '';
if (isset($this->request->get['directory'])) {
$url .= '&directory=' . urlencode($this->request->get['directory']);
}
if (isset($this->request->get['target'])) {
$url .= '&target=' . $this->request->get['target'];
}
if (isset($this->request->get['thumb'])) {
$url .= '&thumb=' . $this->request->get['thumb'];
}
$data['refresh'] = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url, true);
$url = '';
if (isset($this->request->get['directory'])) {
$url .= '&directory=' . urlencode(html_entity_decode($this->request->get['directory'], ENT_QUOTES, 'UTF-8'));
}
if (isset($this->request->get['filter_name'])) {
$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
}
if (isset($this->request->get['target'])) {
$url .= '&target=' . $this->request->get['target'];
}
if (isset($this->request->get['thumb'])) {
$url .= '&thumb=' . $this->request->get['thumb'];
}
$pagination = new Pagination();
$pagination->total = $image_total;
$pagination->page = $page;
$pagination->limit = 16;
$pagination->url = $this->url->link('common/filemanager', 'token=' . $this->session->data['token'] . $url . '&page={page}', true);
$data['pagination'] = $pagination->render();
$this->response->setOutput($this->load->view('common/filemanager', $data));
}
public function upload() {
$this->load->language('common/filemanager');
$json = array();
// Check user has permission
if (!$this->user->hasPermission('modify', 'common/filemanager')) {
$json['error'] = $this->language->get('error_permission');
}
// Make sure we have the correct directory
if (isset($this->request->get['directory'])) {
$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
} else {
$directory = DIR_IMAGE . 'catalog';
}
// Check its a directory
if (!is_dir($directory)) {
$json['error'] = $this->language->get('error_directory');
}
if (!$json) {
if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
// Sanitize the filename
$filename = basename(html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8'));
// Validate the filename length
if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 255)) {
$json['error'] = $this->language->get('error_filename');
}
// Allowed file extension types
$allowed = array(
'jpg',
'jpeg',
'gif',
'png'
);
if (!in_array(utf8_strtolower(utf8_substr(strrchr($filename, '.'), 1)), $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
// Allowed file mime types
$allowed = array(
'image/jpeg',
'image/pjpeg',
'image/png',
'image/x-png',
'image/gif'
);
if (!in_array($this->request->files['file']['type'], $allowed)) {
$json['error'] = $this->language->get('error_filetype');
}
// Return any upload error
if ($this->request->files['file']['error'] != UPLOAD_ERR_OK) {
$json['error'] = $this->language->get('error_upload_' . $this->request->files['file']['error']);
}
} else {
$json['error'] = $this->language->get('error_upload');
}
}
if (!$json) {
move_uploaded_file($this->request->files['file']['tmp_name'], $directory . '/' . $filename);
$json['success'] = $this->language->get('text_uploaded');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function folder() {
$this->load->language('common/filemanager');
$json = array();
// Check user has permission
if (!$this->user->hasPermission('modify', 'common/filemanager')) {
$json['error'] = $this->language->get('error_permission');
}
// Make sure we have the correct directory
if (isset($this->request->get['directory'])) {
$directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this->request->get['directory']), '/');
} else {
$directory = DIR_IMAGE . 'catalog';
}
// Check its a directory
if (!is_dir($directory)) {
$json['error'] = $this->language->get('error_directory');
}
if (!$json) {
// Sanitize the folder name
$folder = str_replace(array('../', '..\\', '..'), '', basename(html_entity_decode($this->request->post['folder'], ENT_QUOTES, 'UTF-8')));
// Validate the filename length
if ((utf8_strlen($folder) < 3) || (utf8_strlen($folder) > 128)) {
$json['error'] = $this->language->get('error_folder');
}
// Check if directory already exists or not
if (is_dir($directory . '/' . $folder)) {
$json['error'] = $this->language->get('error_exists');
}
}
if (!$json) {
mkdir($directory . '/' . $folder, 0777);
chmod($directory . '/' . $folder, 0777);
$json['success'] = $this->language->get('text_directory');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function delete() {
$this->load->language('common/filemanager');
$json = array();
// Check user has permission
if (!$this->user->hasPermission('modify', 'common/filemanager')) {
$json['error'] = $this->language->get('error_permission');
}
if (isset($this->request->post['path'])) {
$paths = $this->request->post['path'];
} else {
$paths = array();
}
// Loop through each path to run validations
foreach ($paths as $path) {
$path = rtrim(DIR_IMAGE . str_replace(array('../', '..\\', '..'), '', $path), '/');
// Check path exsists
if ($path == DIR_IMAGE . 'catalog') {
$json['error'] = $this->language->get('error_delete');
break;
}
}
if (!$json) {
// Loop through each path
foreach ($paths as $path) {
$path = rtrim(DIR_IMAGE . str_replace(array('../', '..\\', '..'), '', $path), '/');
// If path is just a file delete it
if (is_file($path)) {
unlink($path);
// If path is a directory beging deleting each file and sub folder
} elseif (is_dir($path)) {
$files = array();
// Make path into an array
$path = array($path . '*');
// While the path array is still populated keep looping through
while (count($path) != 0) {
$next = array_shift($path);
foreach (glob($next) as $file) {
// If directory add to path array
if (is_dir($file)) {
$path[] = $file . '/*';
}
// Add the file to the files to be deleted array
$files[] = $file;
}
}
// Reverse sort the file array
rsort($files);
foreach ($files as $file) {
// If file just delete
if (is_file($file)) {
unlink($file);
// If directory use the remove directory function
} elseif (is_dir($file)) {
rmdir($file);
}
}
}
}
$json['success'] = $this->language->get('text_delete');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
How can I get all sub-directories of a given directory without files, .(current directory) or ..(parent directory)
and then use each directory in a function?
Option 1:
You can use glob() with the GLOB_ONLYDIR option.
Option 2:
Another option is to use array_filter to filter the list of directories. However, note that the code below will skip valid directories with periods in their name like .config.
$dirs = array_filter(glob('*'), 'is_dir');
print_r($dirs);
Here is how you can retrieve only directories with GLOB:
$directories = glob($somePath . '/*' , GLOB_ONLYDIR);
The Spl DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories.
$dir = new DirectoryIterator($path);
foreach ($dir as $fileinfo) {
if ($fileinfo->isDir() && !$fileinfo->isDot()) {
echo $fileinfo->getFilename().'<br>';
}
}
Almost the same as in your previous question:
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($yourStartingPath),
RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $file) {
if($file->isDir()) {
echo strtoupper($file->getRealpath()), PHP_EOL;
}
}
Replace strtoupper with your desired function.
Try this code:
<?php
$path = '/var/www/html/project/somefolder';
$dirs = array();
// directory handle
$dir = dir($path);
while (false !== ($entry = $dir->read())) {
if ($entry != '.' && $entry != '..') {
if (is_dir($path . '/' .$entry)) {
$dirs[] = $entry;
}
}
}
echo "<pre>"; print_r($dirs); exit;
In Array:
function expandDirectoriesMatrix($base_dir, $level = 0) {
$directories = array();
foreach(scandir($base_dir) as $file) {
if($file == '.' || $file == '..') continue;
$dir = $base_dir.DIRECTORY_SEPARATOR.$file;
if(is_dir($dir)) {
$directories[]= array(
'level' => $level
'name' => $file,
'path' => $dir,
'children' => expandDirectoriesMatrix($dir, $level +1)
);
}
}
return $directories;
}
//access:
$dir = '/var/www/';
$directories = expandDirectoriesMatrix($dir);
echo $directories[0]['level'] // 0
echo $directories[0]['name'] // pathA
echo $directories[0]['path'] // /var/www/pathA
echo $directories[0]['children'][0]['name'] // subPathA1
echo $directories[0]['children'][0]['level'] // 1
echo $directories[0]['children'][1]['name'] // subPathA2
echo $directories[0]['children'][1]['level'] // 1
Example to show all:
function showDirectories($list, $parent = array())
{
foreach ($list as $directory){
$parent_name = count($parent) ? " parent: ({$parent['name']}" : '';
$prefix = str_repeat('-', $directory['level']);
echo "$prefix {$directory['name']} $parent_name <br/>"; // <-----------
if(count($directory['children'])){
// list the children directories
showDirectories($directory['children'], $directory);
}
}
}
showDirectories($directories);
// pathA
// - subPathA1 (parent: pathA)
// -- subsubPathA11 (parent: subPathA1)
// - subPathA2
// pathB
// pathC
You can try this function (PHP 7 required)
function getDirectories(string $path) : array
{
$directories = [];
$items = scandir($path);
foreach ($items as $item) {
if($item == '..' || $item == '.')
continue;
if(is_dir($path.'/'.$item))
$directories[] = $item;
}
return $directories;
}
Non-recursively List Only Directories
The only question that direct asked this has been erroneously closed, so I have to put it here.
It also gives the ability to filter directories.
/**
* Copyright © 2020 Theodore R. Smith <https://www.phpexperts.pro/>
* License: MIT
*
* #see https://stackoverflow.com/a/61168906/430062
*
* #param string $path
* #param bool $recursive Default: false
* #param array $filtered Default: [., ..]
* #return array
*/
function getDirs($path, $recursive = false, array $filtered = [])
{
if (!is_dir($path)) {
throw new RuntimeException("$path does not exist.");
}
$filtered += ['.', '..'];
$dirs = [];
$d = dir($path);
while (($entry = $d->read()) !== false) {
if (is_dir("$path/$entry") && !in_array($entry, $filtered)) {
$dirs[] = $entry;
if ($recursive) {
$newDirs = getDirs("$path/$entry");
foreach ($newDirs as $newDir) {
$dirs[] = "$entry/$newDir";
}
}
}
}
return $dirs;
}
<?php
/*this will do what you asked for, it only returns the subdirectory names in a given
path, and you can make hyperlinks and use them:
*/
$yourStartingPath = "photos\\";
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($yourStartingPath),
RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $file) {
if($file->isDir()) {
$path = strtoupper($file->getRealpath()) ;
$path2 = PHP_EOL;
$path3 = $path.$path2;
$result = end(explode('/', $path3));
echo "<br />". basename($result );
}
}
/* best regards,
Sanaan Barzinji
Erbil
*/
?>
This is the one liner code:
$sub_directories = array_map('basename', glob($directory_path . '/*', GLOB_ONLYDIR));
Proper way
/**
* Get all of the directories within a given directory.
*
* #param string $directory
* #return array
*/
function directories($directory)
{
$glob = glob($directory . '/*');
if($glob === false)
{
return array();
}
return array_filter($glob, function($dir) {
return is_dir($dir);
});
}
Inspired by Laravel
The following recursive function returns an array with the full list of sub directories
function getSubDirectories($dir)
{
$subDir = array();
$directories = array_filter(glob($dir), 'is_dir');
$subDir = array_merge($subDir, $directories);
foreach ($directories as $directory) $subDir = array_merge($subDir, getSubDirectories($directory.'/*'));
return $subDir;
}
Source: https://www.lucidar.me/en/web-dev/how-to-get-subdirectories-in-php/
You can use the glob() function to do this.
Here is some documentation on it:
http://php.net/manual/en/function.glob.php
Find all PHP files recursively. The logic should be simple enough to tweak and it aims to be fast(er) by avoiding function calls.
function get_all_php_files($directory) {
$directory_stack = array($directory);
$ignored_filename = array(
'.git' => true,
'.svn' => true,
'.hg' => true,
'index.php' => true,
);
$file_list = array();
while ($directory_stack) {
$current_directory = array_shift($directory_stack);
$files = scandir($current_directory);
foreach ($files as $filename) {
// Skip all files/directories with:
// - A starting '.'
// - A starting '_'
// - Ignore 'index.php' files
$pathname = $current_directory . DIRECTORY_SEPARATOR . $filename;
if (isset($filename[0]) && (
$filename[0] === '.' ||
$filename[0] === '_' ||
isset($ignored_filename[$filename])
))
{
continue;
}
else if (is_dir($pathname) === TRUE) {
$directory_stack[] = $pathname;
} else if (pathinfo($pathname, PATHINFO_EXTENSION) === 'php') {
$file_list[] = $pathname;
}
}
}
return $file_list;
}
If you're looking for a recursive directory listing solutions. Use below code I hope it should help you.
<?php
/**
* Function for recursive directory file list search as an array.
*
* #param mixed $dir Main Directory Path.
*
* #return array
*/
function listFolderFiles($dir)
{
$fileInfo = scandir($dir);
$allFileLists = [];
foreach ($fileInfo as $folder) {
if ($folder !== '.' && $folder !== '..') {
if (is_dir($dir . DIRECTORY_SEPARATOR . $folder) === true) {
$allFileLists[$folder . '/'] = listFolderFiles($dir . DIRECTORY_SEPARATOR . $folder);
} else {
$allFileLists[$folder] = $folder;
}
}
}
return $allFileLists;
}//end listFolderFiles()
$dir = listFolderFiles('your searching directory path ex:-F:\xampp\htdocs\abc');
echo '<pre>';
print_r($dir);
echo '</pre>'
?>
Find all subfolders under a specified directory.
<?php
function scanDirAndSubdir($dir, &$fullDir = array()){
$currentDir = scandir($dir);
foreach ($currentDir as $key => $filename) {
$realpath = realpath($dir . DIRECTORY_SEPARATOR . $filename);
if (!is_dir($realpath) && $filename != "." && $filename != "..") {
scanDirAndSubdir($realpath, $fullDir);
} else {
$fullDir[] = $realpath;
}
}
return $fullDir;
}
var_dump(scanDirAndSubdir('C:/web2.0/'));
Sample :
array (size=4)
0 => string 'C:/web2.0/config/' (length=17)
1 => string 'C:/web2.0/js/' (length=13)
2 => string 'C:/web2.0/mydir/' (length=16)
3 => string 'C:/web2.0/myfile/' (length=17)
I'm able to parse through the directory and list all images with any of the functions below. I just need to insert a class="last" attribute into the img tag of the last element in the loop.
Also, which of these functions works best for what I'm trying to do?
Any help much appreciated!
function get_images1() {
$exts = 'jpg jpeg png gif';
$str = ''; $i = -1; // Initialize some variables
$folder = './wp-content/uploads';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) { // for each extension check the extension
if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
//$str .= $file;
$str .="<img src='wp-content/uploads/". $file ."' alt='" . $file . "' />";
//if ($str) $str .= '|';
++$i;
}
}
}
echo $str;
closedir($handle); // Were not using it anymore
return $str;
}
function get_images2() {
//Open images directory
$dir = # opendir("wp-content/uploads/");
//List files in uploads directory
while (($file = readdir($dir)) !== false)
{
if(ereg("(.*)\.(jpg|bmp|jpeg|png|gif)", $file))
{
echo '<img src="wp-content/uploads/'. $file .'" alt="" />';
}
}
closedir($dir);
}
function get_images3() {
$dir = 'wp-content/uploads/';
$files = scandir($dir);
//print_r($files);
$num = count($files);
for($n=0; $n<$num; $n++)
{
if(ereg("(.*)\.(jpg|bmp|jpeg|png|gif)", $files[$n]))
{
echo '<img src="wp-content/uploads/'. $files[$n] .'" alt="" />';
}
}
}
function get_images()
{
$directory = 'wp-content/uploads/';
$directory_stream = # opendir($directory);
// Display information about the directory stream
// print_r ($directory_stream);
while ($entry = readdir ($directory_stream))
{
if (! is_file ("$directory/$entry"))
continue;
echo '<img src="wp-content/uploads/'. $entry .'" alt="" />';
}
}
If you don't echo or concatenate the <img> and add the filename to an array you can easily generate the markup you want.
<?php
$dir = 'wp-content/uploads/';
$imgs = array();
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (!is_dir($file) && preg_match("/\.(bmp|jpe?g|gif|png)$/", $file)) {
array_push($imgs, $file);
}
}
closedir($dh);
} else {
die('cannot open ' . $dir);
}
foreach ($imgs as $idx=>$img) {
$class = ($idx == count($imgs) - 1 ? ' class="last"' : '');
echo '<img src="' . $dir . $img . '" alt="' .
$img . '"' . $class . ' />' . "\n";
}
?>
I would use DirectoryIterator to get all files, the filter this using a custom FilterIterator and then a CachingIterator to check for the last element:
class ExtensionFilter extends FilterIterator {
public function accept() {
return $this->current()->isFile() && preg_match("/\.(bmp|jpe?g|gif|png)$/", $this->current()->getBasename());
}
}
$it = new CachingIterator(new ExtensionFilter(new DirectoryIterator($dir)));
foreach ($it as $dir) {
$filename = $dir->getFilename();
echo '<img src="'.$filename.'" '.($it->hasMore() ? '' : ' class="last"').'>';
}