Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum. Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !

CLASSE DIRECTORYITERATOR POUR PHP4


Information sur la source

Catégorie :Class et Objet ( POO ) Classé sous : direrctoryiterator, directory, file, dossier, fichier Niveau : Initié Date de création : 29/05/2007 Date de mise à jour : 30/05/2007 11:42:41 Vu : 4 074

Note :
10 / 10 - par 2 personnes
10,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

Commentaire sur cette source (7)
Ajouter un commentaire et/ou une note

Description

Dans le cadre d'un de mes projets, j'utilise la classe PHP 5 DirectoryIterator vraiment utile pour le parcours de dossier.
Elle utilise les itérateurs et permet donc un parcours plus simple (ca évite de faire des vérifications dans les boucles, contrairement à la classe dir).
Le soucis, c'est qu'elle n'est QUE PHP 5. Je l'ai donc implémentée en PHP 4 afin d'avoir un code fonctionnel, même sur un serveur en PHP 4.

Je vous laisse voir le code :)
 

Source

  • <?php
  • /**
  • * Projet : Directory
  • * File : DirectoryIterator.class.php
  • *
  • * class DirectoryIterator
  • * @author Codefalse <codefalse [at] altern [dot] org>
  • * @copyright Codefalse
  • * @version 20070529
  • * @licence GPL - http://www.gnu.org/licenses/gpl.html - General Public Licence
  • * @version 1.0.0
  • */
  • class DirectoryIterator {
  • /**
  • * Orignal Path
  • *
  • * @var string
  • */
  • var $_sRoot;
  • /**
  • * Opendir ressource
  • *
  • * @var ressource
  • */
  • var $_rOpenDir;
  • /**
  • * Current File
  • *
  • * @var string
  • */
  • var $_sCurrentFile;
  • /**
  • * Starting Offset
  • *
  • * @var int
  • */
  • var $_iOffset = -1;
  • /**
  • * function DirectoryIterator
  • * Constructor
  • * Open the path given and start the reading
  • *
  • * @param string $sPath : The path. Need to finish by / (DIRECTORY_SEPARATOR)
  • *
  • * @return void
  • */
  • function DirectoryIterator ($sPath) {
  • $this->_sRoot = $sPath;
  • clearstatcache ();
  • if (is_dir ($sPath) === true) {
  • $this->_rOpenDir = opendir ($sPath);
  • $this->next();
  • }
  • else {
  • die ('Invalid Path !');
  • }
  • }
  • /**
  • * function current
  • * Get the current element value
  • *
  • * @return string
  • */
  • // @return DirectoryIterator ?!
  • function current () {
  • return $this->_sCurrentFile;
  • }
  • /**
  • * function next
  • * Move to next entry
  • *
  • * @return void
  • */
  • function next () {
  • $this->_sCurrentFile = readdir ($this->_rOpenDir);
  • $this->_iOffset++;
  • }
  • /**
  • * function rewind
  • * Rewind dir back to the start
  • *
  • * @return void
  • */
  • function rewind () {
  • $this->_sCurrentFile = rewinddir ($this->_rOpenDir);
  • $this->_iOffset = -1;
  • $this->next();
  • }
  • /**
  • * function valid
  • * Check whether dir contains more entries
  • *
  • * @return string
  • */
  • function valid () {
  • if ($this->_sCurrentFile === false)
  • return false;
  • else
  • return true;
  • }
  • /**
  • * function key
  • * Return current dir entry
  • *
  • * @return string
  • */
  • // @return string ?!
  • function key () {
  • return $this->_iOffset;
  • }
  • /**
  • * function isDir
  • * Returns true if file is directory
  • *
  • * @return boolean
  • */
  • function isDir () {
  • clearstatcache ();
  • return is_dir ($this->_sRoot.DIRECTORY_SEPARATOR.$this->_sCurrentFile);
  • }
  • /**
  • * function isDot
  • * Returns true if current entry is '.' or '..'
  • *
  • * @return boolean
  • */
  • function isDot () {
  • if ($this->_sCurrentFile == '.' || $this->_sCurrentFile == '..')
  • return true;
  • else return false;
  • }
  • /**
  • * function getATime
  • * return last access time of file
  • *
  • * @return int
  • */
  • function getATime () {
  • clearstatcache ();
  • return fileatime ($this->_sRoot.$this->_sCurrentFile);
  • }
  • /**
  • * function getCTime
  • * Return inode modification time of file
  • *
  • * @return int
  • */
  • function getCTime () {
  • clearstatcache ();
  • return filectime ($this->_sRoot.$this->_sCurrentFile);
  • }
  • /**
  • * function getGroup
  • * Return file group
  • *
  • * @return int
  • */
  • function getGroup () {
  • clearstatcache ();
  • return filegroup ($this->_sRoot.$this->_sCurrentFile);
  • }
  • /**
  • * function getInode
  • * Return file inode
  • *
  • * @return int
  • */
  • function getInode () {
  • clearstatcache ();
  • return fileinode ($this->_sRoot.$this->_sCurrentFile);
  • }
  • /**
  • * function getMTime
  • * Return last modification time of file
  • *
  • * @return int
  • */
  • function getMTime () {
  • clearstatcache ();
  • return filemtime ($this->_sRoot.$this->_sCurrentFile);
  • }
  • /**
  • * function getOwner
  • * Return file owner
  • *
  • * @return int
  • */
  • function getOwner () {
  • clearstatcache ();
  • return fileowner ($this->_sRoot.$this->_sCurrentFile);
  • }
  • /**
  • * function getPerms
  • * Return file permissions
  • *
  • * @return int
  • */
  • function getPerms () {
  • clearstatcache ();
  • return fileperms ($this->_sRoot.$this->_sCurrentFile);
  • }
  • /**
  • * function getSize
  • * Return file size
  • *
  • * @return int
  • */
  • function getSize () {
  • clearstatcache ();
  • if (is_file ($this->_sRoot.$this->_sCurrentFile) === true)
  • return filesize ($this->_sRoot.$this->_sCurrentFile);
  • else return -1;
  • }
  • /**
  • * function getFilename
  • * Return filename of current dir entry
  • *
  • * @return string
  • */
  • function getFilename () {
  • return $this->_sCurrentFile;
  • }
  • /**
  • * function getPath
  • * Return directory path
  • *
  • * @return string
  • */
  • function getPath () {
  • return $this->_sRoot;
  • }
  • /**
  • * function getPathname
  • * Return path and filename of current dir entry
  • *
  • * @return string
  • */
  • function getPathname () {
  • return $this->_sRoot.$this->_sCurrentFile;
  • }
  • /**
  • * function getType
  • * Return file type
  • *
  • * @return string
  • */
  • function getType () {
  • clearstatcache ();
  • return filetype ($this->_sRoot.$this->_sCurrentFile);
  • }
  • /**
  • * function isExecutable
  • * Returns true if file is executable
  • *
  • * @return boolean
  • */
  • function isExecutable () {
  • clearstatcache ();
  • return is_executable ($this->_sRoot.$this->_sCurrentFile);
  • }
  • /**
  • * function isFile
  • * Returns true if file is a regular file
  • *
  • * @return boolean
  • */
  • function isFile () {
  • clearstatcache ();
  • return is_file ($this->_sRoot.$this->_sCurrentFile);
  • }
  • /**
  • * function isLink
  • * Returns true if file is symbolic link
  • *
  • * @return boolean
  • */
  • function isLink () {
  • clearstatcache ();
  • return is_link ($this->_sRoot.$this->_sCurrentFile);
  • }
  • /**
  • * function isReadable
  • * Returns true if file can be read
  • *
  • * @return boolean
  • */
  • function isReadable () {
  • clearstatcache ();
  • return is_readable ($this->_sRoot.$this->_sCurrentFile);
  • }
  • /**
  • * function isWritable
  • * Returns true if file can be written
  • *
  • * @return boolean
  • */
  • function isWritable () {
  • clearstatcache ();
  • return is_writable ($this->_sRoot.$this->_sCurrentFile);
  • }
  • /**
  • * function getChildren
  • * Returns the current entry if it is a directory
  • *
  • * @return DirectoryIterator
  • */
  • function getChildren () {
  • if (is_dir ($this->_sRoot.$this->_sCurrentFile) === true)
  • return new DirectoryIterator ($this->_sRoot.$this->_sCurrentFile.DIRECTORY_SEPARATOR);
  • }
  • }
  • ?>
<?php
/**
 * Projet : Directory
 * File : DirectoryIterator.class.php
 *
 * class DirectoryIterator
 * @author Codefalse <codefalse [at] altern [dot] org>
 * @copyright Codefalse
 * @version 20070529
 * @licence GPL - http://www.gnu.org/licenses/gpl.html - General Public Licence
 * @version 1.0.0
 */


class DirectoryIterator {

	/**
	 * Orignal Path
	 *
	 * @var string
	 */
	var $_sRoot;
	
	/**
	 * Opendir ressource
	 *
	 * @var ressource
	 */
	var $_rOpenDir;
	
	/**
	 * Current File
	 *
	 * @var string
	 */
	var $_sCurrentFile;
	
	/**
	 * Starting Offset
	 *
	 * @var int
	 */
	var $_iOffset = -1;


	/**
	 * function DirectoryIterator
	 * Constructor
	 * Open the path given and start the reading
	 *
	 * @param string $sPath : The path. Need to finish by / (DIRECTORY_SEPARATOR)
	 *
	 * @return void
	 */
	function DirectoryIterator ($sPath) {
		$this->_sRoot = $sPath;
		clearstatcache ();
		if (is_dir ($sPath) === true) {
			$this->_rOpenDir = opendir ($sPath);
			$this->next();
		}
		else {
			die ('Invalid Path !');
		}
	}
	
	/**
	 * function current
	 * Get the current element value
	 *
	 * @return string
	 */
	// @return DirectoryIterator ?!
	function current () {
		return $this->_sCurrentFile;
	}
	
	/**
	 * function next
	 * Move to next entry
	 *
	 * @return void
	 */
	function next () {
		$this->_sCurrentFile = readdir ($this->_rOpenDir);
		$this->_iOffset++;
	}
	
	/**
	 * function rewind
	 * Rewind dir back to the start
	 *
	 * @return void
	 */
	function rewind () {
		$this->_sCurrentFile = rewinddir ($this->_rOpenDir);
		$this->_iOffset = -1;
		$this->next();
	}
	
	/**
	 * function valid
	 * Check whether dir contains more entries
	 *
	 * @return string
	 */
	function valid () {
		if ($this->_sCurrentFile === false) 
			return false;
		else
			return true;
	}

	/**
	 * function key
	 * Return current dir entry
	 *
	 * @return string
	 */
	// @return string ?!
	function key () {
		return $this->_iOffset;
	}
	
	/**
	 * function isDir
	 * Returns true if file is directory
	 *
	 * @return boolean
	 */
	function isDir () {
		clearstatcache ();
		return is_dir ($this->_sRoot.DIRECTORY_SEPARATOR.$this->_sCurrentFile);
	}

	/**
	 * function isDot
	 * Returns true if current entry is '.' or '..'
	 *
	 * @return boolean
	 */
	function isDot () {
		if ($this->_sCurrentFile == '.' || $this->_sCurrentFile == '..')
			return true;
		else return false;
	}

	/**
	 * function getATime
	 * return last access time of file
	 *
	 * @return int
	 */
	function getATime () {
		clearstatcache ();
		return fileatime ($this->_sRoot.$this->_sCurrentFile);
	}

	/**
	 * function getCTime
	 * Return inode modification time of file
	 *
	 * @return int
	 */
	function getCTime () {
		clearstatcache ();
		return filectime ($this->_sRoot.$this->_sCurrentFile);
	}
	
	/**
	 * function getGroup
	 * Return file group
	 *
	 * @return int
	 */
	function getGroup () {
		clearstatcache ();
		return filegroup ($this->_sRoot.$this->_sCurrentFile);
	}
	
	/**
	 * function getInode
	 * Return file inode
	 *
	 * @return int
	 */
	function getInode () {
		clearstatcache ();
		return fileinode ($this->_sRoot.$this->_sCurrentFile);
	}
	
	/**
	 * function getMTime
	 * Return last modification time of file
	 *
	 * @return int
	 */
	function getMTime () {
		clearstatcache ();
		return filemtime ($this->_sRoot.$this->_sCurrentFile);
	}
	
	/**
	 * function getOwner
	 * Return file owner
	 *
	 * @return int
	 */
	function getOwner () {
		clearstatcache ();
		return fileowner ($this->_sRoot.$this->_sCurrentFile);
	}
	
	/**
	 * function getPerms
	 * Return file permissions
	 *
	 * @return int
	 */
	function getPerms () {
		clearstatcache ();
		return fileperms ($this->_sRoot.$this->_sCurrentFile);
	}
	
	/**
	 * function getSize
	 * Return file size
	 *
	 * @return int
	 */
	function getSize () {
		clearstatcache ();
		if (is_file ($this->_sRoot.$this->_sCurrentFile) === true) 
			return filesize ($this->_sRoot.$this->_sCurrentFile);
		else return -1;
	}
	
	/**
	 * function getFilename
	 * Return filename of current dir entry
	 *
	 * @return string
	 */
	function getFilename () {
		return $this->_sCurrentFile;
	}
	
	/**
	 * function getPath
	 * Return directory path
	 *
	 * @return string
	 */
	function getPath () {
		return $this->_sRoot;
	}
	
	/**
	 * function getPathname
	 * Return path and filename of current dir entry
	 *
	 * @return string
	 */
	function getPathname () {
		return $this->_sRoot.$this->_sCurrentFile;
	}
	
	/**
	 * function getType
	 * Return file type
	 *
	 * @return string
	 */
	function getType () {
		clearstatcache ();
		return filetype ($this->_sRoot.$this->_sCurrentFile);
	}
	
	/**
	 * function isExecutable
	 * Returns true if file is executable
	 *
	 * @return boolean
	 */
	function isExecutable () {
		clearstatcache ();
		return is_executable ($this->_sRoot.$this->_sCurrentFile);
	}
	
	/**
	 * function isFile
	 * Returns true if file is a regular file
	 *
	 * @return boolean
	 */
	function isFile () {
		clearstatcache ();
		return is_file ($this->_sRoot.$this->_sCurrentFile);
	}
	
	/**
	 * function isLink
	 * Returns true if file is symbolic link
	 *
	 * @return boolean
	 */
	function isLink () {
		clearstatcache ();
		return is_link ($this->_sRoot.$this->_sCurrentFile);
	}
	
	/**
	 * function isReadable
	 * Returns true if file can be read
	 *
	 * @return boolean
	 */
	function isReadable () {
		clearstatcache ();
		return is_readable ($this->_sRoot.$this->_sCurrentFile);
	}
	
	/**
	 * function isWritable
	 * Returns true if file can be written
	 *
	 * @return boolean
	 */
	function isWritable () {
		clearstatcache ();
		return is_writable ($this->_sRoot.$this->_sCurrentFile);
	}
	
	/**
	 * function getChildren
	 * Returns the current entry if it is a directory
	 *
	 * @return DirectoryIterator
	 */
	function getChildren () {
		if (is_dir ($this->_sRoot.$this->_sCurrentFile) === true)
			return new DirectoryIterator ($this->_sRoot.$this->_sCurrentFile.DIRECTORY_SEPARATOR);
	}
}
?>

Conclusion

Je n'ai pas testé toutes les fonctions donc il se peut qu'il subsiste des bugs. Les fonctions sont très simples donc normallement non, mais on sais jamais :)

Les commentaires sont bien évidement les bienvenus :)
 

Historique

29 mai 2007 12:31:39 :
Ajout de quelques tags
30 mai 2007 11:42:41 :
Prise en compte des commentaires de Naixn :)

Commentaires et avis

signaler à un administrateur
Commentaire de malalam le 29/05/2007 16:54:29 administrateur CS

Hello,

bien, très bien :-) Très bonne idée.
Ca ne marchera pas avec un foreach() vu qu'on est en php4 et que ton itérateur ne fait donc pas appel à la SPL, mais c'est très bien quand même.
J'avais fait la même chose pour un serveur PHP5.0.4 et la classe splFileObject. Toujours pratique ces itérateurs, et une fois qu'on y est habitué, on a du mal à s'en passer!
10 sur 10.

signaler à un administrateur
Commentaire de codefalse le 29/05/2007 17:49:36 administrateur CS

merci pour ton commentaire :)

"Toujours pratique ces itérateurs, et une fois qu'on y est habitué, on a du mal à s'en passer!" => Carrément ! :)

Juste petit soucis pour ma source, dans le constructeur, je doit faire appel à next() car sinon le premier résultat est vide. Peut-on considérer ca comme une erreur ? ... :/

signaler à un administrateur
Commentaire de malalam le 29/05/2007 18:26:17 administrateur CS

Non, et c'est normal à vrai dire : readdir () se comporte comme un itérateur : il renvoie la ligne courante et déplace le pointeur interne sur la ligne suivante.
Donc, tu dois bien récupérer la ligne courante dans ton next. Et donc, pour avoir un résultat, tu dois bel et bien avoir un appel à next avant de faire un current.

signaler à un administrateur
Commentaire de codefalse le 29/05/2007 18:31:57 administrateur CS

ok donc c'est tout bon :)
Bon j'avoue ne rien avoir inventé :) mais ca simplifie quand meme la vie :)

signaler à un administrateur
Commentaire de Naixn le 30/05/2007 10:37:04

Et même pour simplifier le code, plutôt que de faire :

# if (is_executable ($this->sRoot.$this->sCurrentFile) === true)
#   return true;
# else return false;

Tu peux faire :

# return (is_executable ($this->sRoot.$this->sCurrentFile));

Vu que ces appels renvoient déjà TRUE ou FALSE, ça fait redondant de dire "Si c'est TRUE, on renvoie TRUE, et sinon (si c'est FALSE donc), on renvoie FALSE.

Par habitude, je précederais toutes les variables censées être private/protected par des underscore :
# var $_sRoot;
Même si je sais que le concept de private protected n'était pas encore vraiment là dans PHP4, c'est toujours une bonne habitude :p.

A part ça très bien ! Propre, etc. Même la vérification de l'existence de la classe "DirectoryIterator". Tout le monde n'y pense pas, mais c'est pourtant tellement essentiel :p

Bravo en tout cas :)

signaler à un administrateur
Commentaire de codefalse le 30/05/2007 10:49:03 administrateur CS

merci ! :)

C'est vrai que le return (is_executable ($this->sRoot.$this->sCurrentFile));, je n'y avais pas pensé, jvais corriger ca ! :)
Pour les variables privées oué, pourquoi pas :)
jvais voir ca :)
merci en tout cas!

signaler à un administrateur
Commentaire de codefalse le 30/05/2007 11:43:25 administrateur CS

Voila ! Modifications effectuées :)

Ajouter un commentaire

Discussions en rapport avec ce code source dans le forum

TIME OUT HELP [ par ekinoks ] alors voila ... ce code ci desu est un indexeur de ftp... le problemme c'est que quant les serveur son un peu gros, la page n'a pas le temps de tout i Problème upload de fichier [ par Tupac59 ] Bonjour, ce script me permet &#224; un membre d'uploader des fotos dans son dossier. Le probl&#232;me est que lorsque que j'upload une foto, celle-ci Problème de portée de variable URGENT [ par Tupac59 ] Voila le problème: depuis la page précédente je POST ['log2'], dans la page suivante je récupère ce log2 dans la variable $log et cela fonctionne puis valeur input file [ par chamallow ] Bon, ce matin je dois vraiment le faire exprès c'est pas possible grrrrr Voilà je fais un formulaire tout bete pour un upload pour mes tests : &lt;htm Uploader et minituariser un fichier JPEG/GIF sans passer par un directory temporaire [ par amewole ] Comment est il possible d'Uploader et de r&#233;duire la taille de fichier graphique format&nbsp; JPEG/GIF&nbsp; sans&nbsp; passer par un directory&nb diaporama de fichiers php [ par pillets ] BonjourJe souhaiterais faire une diapo de fichiers php, php3 ou html.Cela fonctionnerait comme une galerie d'images avec un bouton "suivant" et "pr&#2 Lecture d'un nom de fichier...2 [ par magicsmacks ] Bonjour, J'avais demandais il y a qq jours ceci : " Bonjour, Je poss&#232;de un dossier sur mon serveur dans lequel le click sur un lien vers fichier est enregistré dans excel pour un suivi [ par dam_37 ] J'ai une page avec 4 liens vers des pdf ou images s'ouvrant dans d'autres fen&#234;tres.J'aimera J'ai un chemin vers un fichier , je voudrai qu'il se crée automatiquement si il n'existe pas [ par ranouf ] Bonjour, J'ai un chemin: /var/www/test/fonctions/voir.php en l'occurence ce "fonctions/voir.php" n'existe pas. Ce que je voudrai savoir c si il exist Probleme de retour a la ligne Parser CSS 2.0 [ par Tortue95 ] Bonjour a tous je suis en train de monter un podcast donc j'ai cree un flux RSS 2.0voici un bout du code du fichier rss.xml:&nbsp;&nbsp; ...&lt;itunes


Nos sponsors

Sondage...

CalendriCode

Juillet 2009
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
2728293031  

Consulter la suite du CalendriCode

Téléchargements

Comparez les prix Nouvelle version

Photothèque Nouveau !



Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés
Temps d'éxécution de la page : 0,858 sec

Google Coop CodeS-SourceS Google Coop CodeS-SourceS


Certaines images présentes sur le site (notament certains avatars) sont issues des collections IconShock, donc si vous souhaitez utiliser ces icons vous devez les acheter, ne les copiez pas et ne utilisez pas dans vos sites et applications sans les avoir commandé.