Analyse du répertoire/fichier PHP
- ScottG
- Proficient


- Inscription: Juil 06, 2010
- Messages: 280
- Status: Online
Alors j'ai fait récemment une fonction permettant d'obtenir tous les fichiers ou dossiers d'un dossier. J'ai pensé Qu'id mettre la fonction ici donc si quelqu'un avait besoin de l'utiliser ou pour voir si quelqu'un avait des améliorations, ils aimeraient partager.
Si quelqu'un trouve cela utile grand s'il y a des questions, préoccupations ou améliorations Id aiment à entendre
PHP Code: [ Select ]
// This funtion will get all files and directories of folder.
function get_tree($config = array()) {
// Setup the defaults. I choose to set it up like this due to how cluttered the normal way looked
$file_types = empty($config['file_types']) ? array() : $config['file_types'];
$path = empty($config['path']) ? __DIR__ : realpath($config['path']);
$include_directories = (empty($config['include_directories']) || $config['include_directories'] === false) ? false : true;
$directories_only = (empty($config['directories_only']) || $config['directories_only'] === false) ? false : true;
$skip_dots = !isset($config['skip_dots']) ? true : (($config['skip_dots'] === false) ? false : true);
$remove_root = !isset($config['remove_root']) ? true : (($config['remove_root'] === false) ? false : true);
// Make an array to hold the paths
$return_array = array();
// Setup the directory
$directory = new RecursiveDirectoryIterator($path);
// Get the directory and files
$objects = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
// Make sure the file types array is empty if $directories_only is set to true
$file_types = ($directories_only) ? array() : $file_types;
// Setup force extenstion add
$force_extenstions = ((empty($file_types) && $include_directories && !$directories_only) || (empty($file_types) && !$include_directories && !$directories_only)) ? true : false;
// See if we want to include directories
if($include_directories || $directories_only) {
// Add to file types
$file_types[] = 'directory';
// Check to see if we what to add the dot paths
if(!$skip_dots) {
// Add to file types
$file_types[] = 'dot_directory';
}
}
// Loop through the directory and files
foreach($objects as $name => $object) {
// Get the info on the path
$info = pathinfo($name);
// Check $force_extenstions
if($force_extenstions) {
// Check to see if we already have the extenstion
if(!in_array($info['extension'], $file_types)) {
// Add the extension
$file_types[] = $info['extension'];
}
}
// Fix blank
$info['extension'] = (empty($info['extension'])) ? ((substr($name,-1) == '.') ? 'dot_directory' : 'directory') : $info['extension'];
// Check for the file types
if(in_array(strtolower($info['extension']), $file_types)) {
// See if we want to remove the root
if($remove_root) {
// Add to the array
$return_array[] = str_replace($path, '', $name);
} else {
// Add to the array
$return_array[] = $name;
}
}
}
// Return the array
return $return_array;
}
// The config array I decided to go this route so I didn't have a bunch of optional variables just to get one functional part of the function
// for example: instead of get_tree(array(),false, true, false); I could simply do get_tree(array("directories_only" => true, "skip_dots" => false));
//
// Config array options
//
// $config = array(
// "file_types" => array('php','js'),
// "path" => '../path/to/folder',
// "include_directories" => true,
// "directories_only" => true,
// "skip_dots" => true,
// "remove_root" => true
// );
//
// "file_types" - This is the extensions of the files you want to find.
// "path" - Path to the folder you want to scan.
// "include_directories" - If set to true this will return both the directories and the files.
// "directories_only" - If this is set to true is will over ride the file_types array and return only the directories.
// "skip_dots" - If this is set to true is will skip over the '.' and '..' paths.
// "remove_root" - This will remove the root directory path up to the path variable set if set to true.
//
// Defaults
//
// "file_types" - array().
// "path" - __DIR__.
// "include_directories" - false.
// "directories_only" - false.
// "skip_dots" - true.
// "remove_root" - true.
//
// Usage
//
// Get all files only
$test = get_tree();
// Get only php files
$test = get_tree(array("file_types" => array('php')));
// Get php and js files
$test = get_tree(array("file_types" => array('php', js)));
// Get only php files and the subdirectories
$test = get_tree(array("file_types" => array('php'), "include_directories" => true));
// Get only directories
$test = get_tree(array("directories_only" => true));
// Get only directories with dot paths
$test = get_tree(array("directories_only" => true, "skip_dots" => false));
// Get all files with root path
$test = get_tree(array("remove_root" => false));
function get_tree($config = array()) {
// Setup the defaults. I choose to set it up like this due to how cluttered the normal way looked
$file_types = empty($config['file_types']) ? array() : $config['file_types'];
$path = empty($config['path']) ? __DIR__ : realpath($config['path']);
$include_directories = (empty($config['include_directories']) || $config['include_directories'] === false) ? false : true;
$directories_only = (empty($config['directories_only']) || $config['directories_only'] === false) ? false : true;
$skip_dots = !isset($config['skip_dots']) ? true : (($config['skip_dots'] === false) ? false : true);
$remove_root = !isset($config['remove_root']) ? true : (($config['remove_root'] === false) ? false : true);
// Make an array to hold the paths
$return_array = array();
// Setup the directory
$directory = new RecursiveDirectoryIterator($path);
// Get the directory and files
$objects = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
// Make sure the file types array is empty if $directories_only is set to true
$file_types = ($directories_only) ? array() : $file_types;
// Setup force extenstion add
$force_extenstions = ((empty($file_types) && $include_directories && !$directories_only) || (empty($file_types) && !$include_directories && !$directories_only)) ? true : false;
// See if we want to include directories
if($include_directories || $directories_only) {
// Add to file types
$file_types[] = 'directory';
// Check to see if we what to add the dot paths
if(!$skip_dots) {
// Add to file types
$file_types[] = 'dot_directory';
}
}
// Loop through the directory and files
foreach($objects as $name => $object) {
// Get the info on the path
$info = pathinfo($name);
// Check $force_extenstions
if($force_extenstions) {
// Check to see if we already have the extenstion
if(!in_array($info['extension'], $file_types)) {
// Add the extension
$file_types[] = $info['extension'];
}
}
// Fix blank
$info['extension'] = (empty($info['extension'])) ? ((substr($name,-1) == '.') ? 'dot_directory' : 'directory') : $info['extension'];
// Check for the file types
if(in_array(strtolower($info['extension']), $file_types)) {
// See if we want to remove the root
if($remove_root) {
// Add to the array
$return_array[] = str_replace($path, '', $name);
} else {
// Add to the array
$return_array[] = $name;
}
}
}
// Return the array
return $return_array;
}
// The config array I decided to go this route so I didn't have a bunch of optional variables just to get one functional part of the function
// for example: instead of get_tree(array(),false, true, false); I could simply do get_tree(array("directories_only" => true, "skip_dots" => false));
//
// Config array options
//
// $config = array(
// "file_types" => array('php','js'),
// "path" => '../path/to/folder',
// "include_directories" => true,
// "directories_only" => true,
// "skip_dots" => true,
// "remove_root" => true
// );
//
// "file_types" - This is the extensions of the files you want to find.
// "path" - Path to the folder you want to scan.
// "include_directories" - If set to true this will return both the directories and the files.
// "directories_only" - If this is set to true is will over ride the file_types array and return only the directories.
// "skip_dots" - If this is set to true is will skip over the '.' and '..' paths.
// "remove_root" - This will remove the root directory path up to the path variable set if set to true.
//
// Defaults
//
// "file_types" - array().
// "path" - __DIR__.
// "include_directories" - false.
// "directories_only" - false.
// "skip_dots" - true.
// "remove_root" - true.
//
// Usage
//
// Get all files only
$test = get_tree();
// Get only php files
$test = get_tree(array("file_types" => array('php')));
// Get php and js files
$test = get_tree(array("file_types" => array('php', js)));
// Get only php files and the subdirectories
$test = get_tree(array("file_types" => array('php'), "include_directories" => true));
// Get only directories
$test = get_tree(array("directories_only" => true));
// Get only directories with dot paths
$test = get_tree(array("directories_only" => true, "skip_dots" => false));
// Get all files with root path
$test = get_tree(array("remove_root" => false));
- // This funtion will get all files and directories of folder.
- function get_tree($config = array()) {
- // Setup the defaults. I choose to set it up like this due to how cluttered the normal way looked
- $file_types = empty($config['file_types']) ? array() : $config['file_types'];
- $path = empty($config['path']) ? __DIR__ : realpath($config['path']);
- $include_directories = (empty($config['include_directories']) || $config['include_directories'] === false) ? false : true;
- $directories_only = (empty($config['directories_only']) || $config['directories_only'] === false) ? false : true;
- $skip_dots = !isset($config['skip_dots']) ? true : (($config['skip_dots'] === false) ? false : true);
- $remove_root = !isset($config['remove_root']) ? true : (($config['remove_root'] === false) ? false : true);
- // Make an array to hold the paths
- $return_array = array();
- // Setup the directory
- $directory = new RecursiveDirectoryIterator($path);
- // Get the directory and files
- $objects = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
- // Make sure the file types array is empty if $directories_only is set to true
- $file_types = ($directories_only) ? array() : $file_types;
- // Setup force extenstion add
- $force_extenstions = ((empty($file_types) && $include_directories && !$directories_only) || (empty($file_types) && !$include_directories && !$directories_only)) ? true : false;
- // See if we want to include directories
- if($include_directories || $directories_only) {
- // Add to file types
- $file_types[] = 'directory';
- // Check to see if we what to add the dot paths
- if(!$skip_dots) {
- // Add to file types
- $file_types[] = 'dot_directory';
- }
- }
- // Loop through the directory and files
- foreach($objects as $name => $object) {
- // Get the info on the path
- $info = pathinfo($name);
- // Check $force_extenstions
- if($force_extenstions) {
- // Check to see if we already have the extenstion
- if(!in_array($info['extension'], $file_types)) {
- // Add the extension
- $file_types[] = $info['extension'];
- }
- }
- // Fix blank
- $info['extension'] = (empty($info['extension'])) ? ((substr($name,-1) == '.') ? 'dot_directory' : 'directory') : $info['extension'];
- // Check for the file types
- if(in_array(strtolower($info['extension']), $file_types)) {
- // See if we want to remove the root
- if($remove_root) {
- // Add to the array
- $return_array[] = str_replace($path, '', $name);
- } else {
- // Add to the array
- $return_array[] = $name;
- }
- }
- }
- // Return the array
- return $return_array;
- }
- // The config array I decided to go this route so I didn't have a bunch of optional variables just to get one functional part of the function
- // for example: instead of get_tree(array(),false, true, false); I could simply do get_tree(array("directories_only" => true, "skip_dots" => false));
- //
- // Config array options
- //
- // $config = array(
- // "file_types" => array('php','js'),
- // "path" => '../path/to/folder',
- // "include_directories" => true,
- // "directories_only" => true,
- // "skip_dots" => true,
- // "remove_root" => true
- // );
- //
- // "file_types" - This is the extensions of the files you want to find.
- // "path" - Path to the folder you want to scan.
- // "include_directories" - If set to true this will return both the directories and the files.
- // "directories_only" - If this is set to true is will over ride the file_types array and return only the directories.
- // "skip_dots" - If this is set to true is will skip over the '.' and '..' paths.
- // "remove_root" - This will remove the root directory path up to the path variable set if set to true.
- //
- // Defaults
- //
- // "file_types" - array().
- // "path" - __DIR__.
- // "include_directories" - false.
- // "directories_only" - false.
- // "skip_dots" - true.
- // "remove_root" - true.
- //
- // Usage
- //
- // Get all files only
- $test = get_tree();
- // Get only php files
- $test = get_tree(array("file_types" => array('php')));
- // Get php and js files
- $test = get_tree(array("file_types" => array('php', js)));
- // Get only php files and the subdirectories
- $test = get_tree(array("file_types" => array('php'), "include_directories" => true));
- // Get only directories
- $test = get_tree(array("directories_only" => true));
- // Get only directories with dot paths
- $test = get_tree(array("directories_only" => true, "skip_dots" => false));
- // Get all files with root path
- $test = get_tree(array("remove_root" => false));
Si quelqu'un trouve cela utile grand s'il y a des questions, préoccupations ou améliorations Id aiment à entendre
- Anonymous
- Bot


- Inscription: 25 Feb 2008
- Messages: ?
- Loc: Ozzuland
- Status: Online
Décembre 7th, 2012, 1:25 pm
- spork
- Brewmaster


- Inscription: Sep 22, 2003
- Messages: 6134
- Loc: Seattle, WA
- Status: Offline
- ScottG
- Proficient


- Inscription: Juil 06, 2010
- Messages: 280
- Status: Online
Cette fonction analyse tous les sous-répertoires du dossier donné et tire parti de la classe RecursiveDirectoryIterator qui réduit la quantité de code nécessaire pour exécuter la même tâche avec scandir
Par exemple
Je n'ai pas testé les différences de performances entre les deux.
Par exemple
PHP Code: [ Select ]
<?php
// Quick recursive scandir
function recursiveScanDir($dir){
$files = scandir($dir);
foreach($files as $file){
if ($file != '.' && $file != '..'){
if (is_dir($dir . DIRECTORY_SEPARATOR . $file)){
recursiveScanDir($dir . DIRECTORY_SEPARATOR . $file);
}else{
echo $dir . DIRECTORY_SEPARATOR . $file . PHP_EOL . '<br>';
}
}
}
}
recursiveScanDir(__DIR__);
?>
<br>
<br>
<?php
// RecursiveDirectoryIterator in this function
$directory = new RecursiveDirectoryIterator(__DIR__);
$objects = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object) {
echo $name. '<br>';
}
?>
// Quick recursive scandir
function recursiveScanDir($dir){
$files = scandir($dir);
foreach($files as $file){
if ($file != '.' && $file != '..'){
if (is_dir($dir . DIRECTORY_SEPARATOR . $file)){
recursiveScanDir($dir . DIRECTORY_SEPARATOR . $file);
}else{
echo $dir . DIRECTORY_SEPARATOR . $file . PHP_EOL . '<br>';
}
}
}
}
recursiveScanDir(__DIR__);
?>
<br>
<br>
<?php
// RecursiveDirectoryIterator in this function
$directory = new RecursiveDirectoryIterator(__DIR__);
$objects = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object) {
echo $name. '<br>';
}
?>
- <?php
- // Quick recursive scandir
- function recursiveScanDir($dir){
- $files = scandir($dir);
- foreach($files as $file){
- if ($file != '.' && $file != '..'){
- if (is_dir($dir . DIRECTORY_SEPARATOR . $file)){
- recursiveScanDir($dir . DIRECTORY_SEPARATOR . $file);
- }else{
- echo $dir . DIRECTORY_SEPARATOR . $file . PHP_EOL . '<br>';
- }
- }
- }
- }
- recursiveScanDir(__DIR__);
- ?>
- <br>
- <br>
- <?php
- // RecursiveDirectoryIterator in this function
- $directory = new RecursiveDirectoryIterator(__DIR__);
- $objects = new RecursiveIteratorIterator($directory, RecursiveIteratorIterator::SELF_FIRST);
- foreach($objects as $name => $object) {
- echo $name. '<br>';
- }
- ?>
Je n'ai pas testé les différences de performances entre les deux.
- demonmaestro
- Gold Member


- Inscription: Juin 21, 2006
- Messages: 487
- Loc: Conroe, Texas
- Status: Offline
bonne idée mais il ya une erreur...
et cette ligne est
Quote:
Fatal error : Uncaught exception « RuntimeException » avec le nom d'annuaire de message ne doit pas être vide. en /test.php:22 la trace de pile : #/test.php(22) 0: RecursiveDirectoryIterator -> __construct() #1 {main} levée dans /test.php sur la ligne 22
et cette ligne est
PHP Code: [ Select ]
$directory = new RecursiveDirectoryIterator($path);
Thanks, Josh --DemonMaestro
www.LilNetwork.com
Fun Website www.ShoutsCloud.com
www.LilNetwork.com
Fun Website www.ShoutsCloud.com
- ScottG
- Proficient


- Inscription: Juil 06, 2010
- Messages: 280
- Status: Online
Qui est du deuxième bloc de code ? Si c'est le cas, j'ai copié le cœur de la fonction ci-dessus et j'ai oublié d'ajouter un chemin d'accès. J'ai aussi n'évaluait pas la deuxième partie parce que je me donne un exemple. J'ai fait le changement et, si vous tournez
Alors que l'erreur devrait disparaître
PHP Code: [ Select ]
$directory = new RecursiveDirectoryIterator($path);
// To
$directory = new RecursiveDirectoryIterator(__DIR__);
// Or
$directory = new RecursiveDirectoryIterator('/your/folder/path');
// To
$directory = new RecursiveDirectoryIterator(__DIR__);
// Or
$directory = new RecursiveDirectoryIterator('/your/folder/path');
- $directory = new RecursiveDirectoryIterator($path);
- // To
- $directory = new RecursiveDirectoryIterator(__DIR__);
- // Or
- $directory = new RecursiveDirectoryIterator('/your/folder/path');
Alors que l'erreur devrait disparaître
Page 1 sur 1
Pour répondre à ce sujet, vous devez vous connecter ou vous enregistrer. Il est gratuit.
Afficher de l'information
- Total des messages de ce sujet: 5 messages
- Utilisateurs parcourant ce forum: Aucun utilisateur enregistré et 200 invités
- Vous ne pouvez pas poster de nouveaux sujets
- Vous ne pouvez pas répondre aux sujets
- Vous ne pouvez pas éditer vos messages
- Vous ne pouvez pas supprimer vos messages
- Vous ne pouvez pas joindre des fichiers
