The following code counts the number of files inside a folder.
<?php
function folderlist(){
$directoryist = array();
$startdir = './';
//get all image files with a .jpg extension.
$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';
if (is_dir($startdir)){
if ($dh = opendir($startdir)){
while (($folder = readdir($dh)) !== false){
if (!(array_search($folder,$ignoredDirectory) > -1)){
if (filetype($startdir . $folder) == "dir"){
$directorylist[$startdir . $folder]['name'] = $folder;
$directorylist[$startdir . $folder]['path'] = $startdir;
}
}
}
closedir($dh);
}
}
return($directorylist);
}
$folders = folderlist();
$total_files = 0;
foreach ($folders as $folder){
$path = $folder['path'];
$name = $folder['name'];
$count = iterator_count(new DirectoryIterator($path . $name));
$total_files += $count;
echo '<li>';
echo '<a href="' .$path .'index.php?album=' .$name . '" class="style1">';
echo '<strong>' . $name . '</strong>';
echo ' (' . $count . ' files found)';
echo '</a>';
echo '</li>';
}
echo "Total Files:". $total_files;
?>
However for some reason the count is off by 2. I have a folder with 13 files but this code returns count as 15. For an empty folder, this returns a count of 2.
Can someone point to me the issue with the above snippet?
I'm doing it with DirectoryIterator
$files_in_directory = new DirectoryIterator($path_to_folder);
$c = 0;
foreach($files_in_directory as $file)
{
// We want only files
if($file->isDot()) continue;
if($file->isDir()) continue;
$c++;
}
var_dump($c);
For use as function :
function folderlist($directories = array(), $extensions = array())
{
if(empty($directories))
return false;
$result = array();
$total_count = 0;
foreach($directories as $directory)
{
$files_in_directory = new DirectoryIterator($directory);
$c = 0;
foreach($files_in_directory as $file)
{
// We want only files
if($file->isDot()) continue;
if($file->isDir()) continue;
// This is for php < 5.3.6
$file_extension = pathinfo($file->getFilename(), PATHINFO_EXTENSION);
// If you have php >= 5.3.6 you can use following instead
// $file_extension = $fileinfo->getExtension()
if(in_array($file_extension, $extensions)){
$c++;
$result['directories'][$directory]['files'][$c]['name'] = $file->getFilename();
$result['directories'][$directory]['files'][$c]['path'] = $file->getPath();
$result['directories'][$directory]['count'] = $c;
}
}
$total_count += $c;
}
$result['total_count'] = $total_count;
return $result;
}
Displaying results based on GET superglobal:
if(isset($_GET['album']) && !empty($_GET['album']) && !isset($_GET['listfiles']))
{
// We are in directory view mode
$album = $_GET['album'];
// View all directories and their file count for specified album
$view_directory = folderlist(array($album), array('jpeg', 'jpg', 'log'));
// Loop the folders and display them with file count
foreach ($view_directory['directories'] as $folder_name => $folder_files){
$count = $folder_files['count'];
echo '<li>';
echo '<a href="files.php?album=' . $folder_name . '&listfiles=1" class="style1">';
echo '<strong>' . basename($folder_name) . '</strong>';
echo ' (' . $count . ' files found)';
echo '</a>';
echo '</li>';
}
echo "Total Files:". $get_dir_info['total_count'];
}
elseif(isset($_GET['album'], $_GET['listfiles']) && !empty($_GET['album']))
{
// We are in file view mode for folder
$album = $_GET['album'];
// View all files in directory
$view_files = folderlist(array($album), array('jpeg', 'jpg', 'log'));
echo 'Showing folder content of: <b>'.basename($album).'</b>';
foreach($view_files['directories'][$album]['files'] as $file)
{
$path = $file['path'];
$name = $file['name'];
echo '<li>';
echo '<a href="files.php?file=' . $name . '&path=' . $path . '" class="style1">';
echo '<strong>' . $name . '</strong>';
echo '</a>';
echo '</li>';
}
}
This line is still returning the '.' and '..' vars.
if (!(array_search($folder,$ignoredDirectory) > -1))
see: http://php.net/manual/en/language.types.boolean.php
Try
if (!array_search($folder,$ignoredDirectory))
EDIT:
Also change this:
$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';
to
$ignoredDirectory = array( '.', '..' );
Related
I have one little question, this is my code to list all files from a folder and subfolders;
if ($handle = opendir($dir)) {
$allFiles = array();
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if (is_dir($dir . "/" . $entry)){
$allFiles[] = "D: " . $dir . "/" . $entry;
}else{
$extension = strtoupper(pathinfo($entry, PATHINFO_EXTENSION));
$fileNoExten = pathinfo($entry, PATHINFO_FILENAME);
$directory = substr(str_replace('/', ' > ', $dir), $rootLenOnce + 3);
$listagem .= '<tr>';
$listagem .= "<td><a href='../" . $dir . "/" . $entry . "' ' target='_blank'>" . $entry . "</a></td>";
//$listagem .= "<td><small>" . $directory . "</small></td>";
$listagem .= "<td>" . $extension . "</td>";
$listagem .= "<td><a class='download-cell' href='../".$dir ."/". $entry."' ' download> <i class='fa fa-download' ></i></a></td>";
$listagem .= "<td class='display-none'>" . $fileNoExten . "</td>";
$allFiles[] = "F: " . $dir . "/" . $entry;
$listagem .= '</tr>';
echo "<pre>"; print_r(glob("*.pdf")); echo "</pre>";
}
}
}
closedir($handle);
foreach($allFiles as $value){
$displayName = substr($value, $rootLen + 4);
$fileName = substr($value, 3);
$linkName = str_replace(" ", "%20", substr($value, $pathLen + 3));
if (is_dir($fileName)) {
myScanDirPdf($fileName, $level + 1, strlen($fileName),$rootLenOnce);
}
}
}
return $listagem;
}
what i need is to filtrate the search, to search only .pdf files.
Someone can help me plz!
Thks!
i try with the glob function, but not with great results.
Thks!
When you are looping through each file, you can use
if(stripos($fileName, ".pdf"))
Hope this will help
I have one more suggestion in listing all the files and subfolders.
You can use Recursive Iterator
$folderName = $_POST['folderName'];
$dir = new RecursiveDirectoryIterator($folderName);
$it = new RecursiveIteratorIterator($dir);
foreach ($it as $fileinfo) {
if ($fileinfo->isDir()) {
}elseif ($fileinfo->isFile()) {
$fileName = $fileinfo->getFileName();
if(stripos($fileName, ".pdf")) {
//do what you need to do
}
}
}
The code works perfectly. Just don't know how to get it to display the content randomly without using Jquery.
Got it to display a random image from the current directory, but not sure how to get the directory to display randomly.
$dir = 'img/series_thumbnail/';
$dh = opendir($dir);
while (($fileName = readdir($dh)) !== false) {
if (!in_array($fileName, array('.', '..'))) {
$images = glob($dir . $fileName . '/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$imgMax = count($images)-1;
$imgNum = rand(0, $imgMax);
$imgUrl = $images[$imgNum];
echo '<li>';
echo '<img src="' . $imgUrl . '"/>';
echo '<div class="info"><p>' . $fileName . '</p></div>';
echo '</li>';
}
}
Thank you.
EDIT
Figured it out! Thanks for your help everyone.
$dir = glob("img/series_thumbnail/*", GLOB_ONLYDIR);
shuffle($dir);
foreach ($dir as $folder) {
if (!in_array($folder, array(".", ".."))) {
$folderName = basename($folder).PHP_EOL;
$images = glob($folder . "/*.{jpg,jpeg,png,gif}", GLOB_BRACE);
shuffle($images);
echo "<li>";
echo '<img src="' . $images[0] . '"/>';
echo "<div class='info'><p>" . $folderName . "</p></div>";
echo "</li>";
}
}
If you want to display a single random image from each directory, with the directories in random order, you can use this code:
$dir = 'img/series_thumbnail/';
$directories = glob("$dir*", GLOB_ONLYDIR);
shuffle($directories);
foreach ($directories as $directory) {
$images = glob($dir . $directory. '/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$imgMax = count($images)-1;
$imgNum = rand(0, $imgMax);
$imgUrl = $images[$imgNum];
echo '<li>';
echo '<img src="' . $imgUrl . '"/>';
echo '<div class="info"><p>' . $fileName . '</p></div>';
echo '</li>';
}
I used the code from this website http://wiki.slideshowpro.net/PlayerWithoutDirector/PWDSCRIPTS-PHPXMLBuilderScript with a copy of the code below called images.php with audio but I don't really need audio. This PHP script just retrieves the image source of photos in a directory of a folder to an XML file. Instead, I'd like to write an XML file that would get the image source directly from a SlideshowPro Album. The first code below lists the images from an album directly from SlideShowPro. How do I combine the two scripts?
// gallery.php
<?php
include('classes/DirectorPHP.php');
$director = new Director('api', 'key');
$album = $director->album->get(440);
echo $album->name . '<br /><br />';
// Loop through album content
$contents = $album->contents[0];
foreach($contents as $content) {
echo $content->src . '<br />';
}
?>
// images.php
<?php
/**************************************************************************
XML Generator for SlideShowPro
Brad Daily - slideshowpro.net
For instructions, see the wiki:
http://wiki.slideshowpro.net/SSPExtras/PhpXmlBuilder
This script is governed by the following license:
http://creativecommons.org/licenses/by-nc-sa/3.0/us/
**************************************************************************/
/*
CONFIGURATION
*/
// Name of the folder in each album's folder that contains the full size imagery
$large_folder = 'lg';
// Name of the folder in each album's folder that contains the thumbnails
$thumb_folder = 'tn';
// Name of your album preview image. placed at the root of each album's folder (optional)
$album_preview_name = 'albumPreview.jpg';
/* Audio addition
$audio_folder = 'audio';
*/
/*
END CONFIGURATION
(DO NOT EDIT BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING)
*/
// Set up paths
define('DS', DIRECTORY_SEPARATOR);
$dir = dirname(__FILE__);
$server = 'http://' . $_SERVER['HTTP_HOST'];
$rel_path = str_replace('images.php', '', $_SERVER['PHP_SELF']);
$path = $server . $rel_path;
$iptc = is_callable('iptcparse');
/*$width = "thumbnailWidth=auto thumbnailHeight=78"; */
// Find all folders in this directory
$albums = array();
$d = dir($dir);
while (false !== ($folder = $d->read())) {
if ($folder != '.' && $folder != '..' && is_dir($dir . DS . $folder . DS . $large_folder))
{
$albums[] = $folder;
}
}
$d->close();
// Start writing XML
$o = '<?xml version="1.0" encoding="utf-8"?>' . "\n<galleries>\n";
// Cycle through albums
foreach($albums as $album) {
// Path variables
$loc_path = $path . $album . '/';
$full_path = $dir . DS . $album;
// Find images in the large folder
$images = array();
$d2 = dir($full_path . DS . $large_folder);
while (false !== ($image = $d2->read())) {
if (eregi('.jpg|.gif|.png|.swf|.flv|.mov', $image)) {
$images[] = $image;
}
}
$d2->close();
/* Audio addition
// Find audios in the audio folder
$audios = array();
$d2 = dir($full_path . DS . $audio_folder);
while (false !== ($audio = $d2->read())) {
if (eregi('.mp3|.ra|.wav', $audio)) {
$audios[] = $audio;
}
}
$d2->close();
Audio addition */
// Only write the album to XML if there are images
if (!empty($images)) {
natcasesort($images);
// Pretty up the title
$title = ucwords(preg_replace('/_|-/', ' ', $album));
// See if there is an album thumb present, if so add it in
if (file_exists($full_path . DS . $album_preview_name)) {
$atn = ' tn="' . $loc_path . $album_preview_name . '"';
} else {
$atn = '';
}
// Only write tnPath if that folder exists
if (is_dir($full_path . DS . $thumb_folder)) {
$tn = ' tnPath="' . $loc_path . $thumb_folder . '/"';
}
/* Audio addition
$audio = '';
if (0 < count($audios)) {
$audio = sprintf(' audio="%s" audioCaption="%s"',
$loc_path . $audio_folder . '/' . $audios[0],
substr(ucwords(preg_replace('/_|-/', ' ', $audios[0])), 0, -4));
}
Audio addition */
// Album tag
$o .= "\t" . '<imagegroup title="' . $title . '" thumbnailPath="' . $loc_path .
$large_folder . '/"' . $width . $atn . $audio . '>' . "\n";
// Cycle through images, adding tag for each to XML
foreach($images as $i) {
$link = $caption = '';
$title = '';
if ($iptc) {
$file = $full_path . DS . $large_folder . DS . $i;
$path_info = pathinfo($file);
$extensions = array('jpg', 'jpeg', 'gif', 'png');
if (in_array(strtolower($path_info['extension']), $extensions)) {
getimagesize($file, $info);
if (!empty($info['APP13'])) {
$iptc = iptcparse($info['APP13']);
if (isset($iptc['2#005'])) {
$title = $iptc['2#005'];
if (is_array($title)) {
$title = htmlentities($title[0], ENT_COMPAT);
}
}
if (isset($iptc['2#120'])) {
$caption = $iptc['2#120'];
if (is_array($caption)) {
$caption = htmlentities($caption[0], ENT_COMPAT);
}
}
}
}
}
if (isset($_GET['link'])) { $link = $loc_path . $large_folder . '/' . $i; }
$o .= "\t\t" . '<img src="' . $i . '" title="' . $title . '" />' . "\n";
}
// Close the album tag
$o .= "\t</imagegroup>\n";
}
}
// Close gallery tag, set header and output XML
$o .= "</galleries>";
header('Content-type: text/xml');
die($o);
I'd like my result to appear like this:
<galleries>
<imagegroup title="2013 In Review" thumbnailPath="2013Review/thumb.jpg" thumbnailWidth="auto" thumbnailHeight="78">
<img src="2013Review/JLP09509_01_026.jpg" title="Paul Walker by Jeff Lipsky"/>
<img src="2013Review/NAB10003_01_001.jpg" title="Nelson Mandela by Nabil"/>
<img src="2013Review/MMU13110_41_001.jpg" title="Lindsey Vonn by Michael Muller"/>
</imagegroup>
<imagegroup title="Awards Season" thumbnailPath="AwardSeason/thumb.jpg" thumbnailWidth="56" thumbnailHeight="78">
<img src="AwardSeason/GBE07090_04_007.jpg" title="Tom Hanks by Giuliano Bekor - "Captain Phillips""/>
<img src="AwardSeason/DTI12009_02_001.jpg" title="Amy Adams by Darren Tieste - "American Hustle" "/>
<img src="AwardSeason/NPA11013_01_005.jpg" title="Idris Elba by Nigel Parry - "Mandela-Long Walk to Freedom" "/>
</imagegroup>
</galleries>
how to folder sortout by time example i create last/latest folder in directory so last folder show on top.
here is code to show directory only
<?php
function folderlist(){
$startdir = './';
$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';
if (is_dir($startdir)){
if ($dh = opendir($startdir)){
while (($folder = readdir($dh)) !== false){
if (!(array_search($folder,$ignoredDirectory) > -1)){
if (filetype($startdir . $folder) == "dir"){
$directorylist[$startdir . $folder]['name'] = $folder;
$directorylist[$startdir . $folder]['path'] = $startdir;
}
}
}
closedir($dh);
}
}
return($directorylist);
}
$folders = folderlist();
foreach ($folders as $folder){
$path = $folder['path'];
$name = $folder['name'];
echo '<li><font face="Tahoma" class="ws10"><B>' . $name . '</B><br /></li>';
}
?>
To do that, you'll need to first grab the created time for the folder, and add that as the start of the key for the array item, then you'll be able to sort based on the key... something like this
<?php
function folderlist(){
$directorylist = array();
$startdir = './';
$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';
if (is_dir($startdir)){
if ($dh = opendir($startdir)){
while (($folder = readdir($dh)) !== false){
if (!(array_search($folder,$ignoredDirectory) > -1)){
if (filetype($startdir . $folder) == "dir"){
$created = filectime($startdir . $folder);
$directorylist[$created . $startdir . $folder]['name'] = $folder;
$directorylist[$created . $startdir . $folder]['path'] = $startdir;
}
}
}
closedir($dh);
}
}
ksort($directorylist);
return($directorylist);
}
$folders = folderlist();
$total_files = 0;
foreach ($folders as $folder){
$path = $folder['path'];
$name = $folder['name'];
$count = iterator_count(new DirectoryIterator($path . $name));
$total_files += $count;
echo '<li>';
echo '<a href="' .$path .'index.php?album=' .$name . '" class="style1">';
echo '<strong>' . $name . '</strong>';
echo ' (' . $count . ' files found)';
echo '</a>';
echo '</li>';
}
echo "Total Files:". $total_files;
?>
Note the new $created variable in use, and also the ksort() method being used to sort the array by its key.
You could sort in reverse order ising krsort.
You could also change the ordering to be based on the modified date, by using filemtime() instead of filectime()
this code showing directory only but i want to show directory with counts files inside the folder
example
count files inside the folder
FolderA (2 Files Found)
FolderB (19 Files Found)
FolderD (1 Files Found)
FolderD (13 Files Found)
function folderlist(){
$startdir = './';
$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';
if (is_dir($startdir)){
if ($dh = opendir($startdir)){
while (($folder = readdir($dh)) !== false){
if (!(array_search($folder,$ignoredDirectory) > -1)){
if (filetype($startdir . $folder) == "dir"){
$directorylist[$startdir . $folder]['name'] = $folder;
$directorylist[$startdir . $folder]['path'] = $startdir;
}
}
}
closedir($dh);
}
}
return($directorylist);
}
$folders = folderlist();
foreach ($folders as $folder){
$path = $folder['path'];
$name = $folder['name'];
echo '<li><font face="Tahoma" class="ws10"><B>' . $name . '</B><br /></li>';
}
?>
Something like this should help you out:
$count = iterator_count(new DirectoryIterator($path));
http://au1.php.net/iterator_count
So:
<?php
function folderlist(){
$directoryist = array();
$startdir = './';
$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';
if (is_dir($startdir)){
if ($dh = opendir($startdir)){
while (($folder = readdir($dh)) !== false){
if (!(array_search($folder,$ignoredDirectory) > -1)){
if (filetype($startdir . $folder) == "dir"){
$directorylist[$startdir . $folder]['name'] = $folder;
$directorylist[$startdir . $folder]['path'] = $startdir;
}
}
}
closedir($dh);
}
}
return($directorylist);
}
$folders = folderlist();
$total_files = 0;
foreach ($folders as $folder){
$path = $folder['path'];
$name = $folder['name'];
$count = iterator_count(new DirectoryIterator($path . $name));
$total_files += $count;
echo '<li>';
echo '<a href="' .$path .'index.php?album=' .$name . '" class="style1">';
echo '<strong>' . $name . '</strong>';
echo ' (' . $count . ' files found)';
echo '</a>';
echo '</li>';
}
echo "Total Files:". $total_files;
?>
Using Sizeof()
http://php.net/manual/en/function.sizeof.php
<?php
function folderlist(){
$startdir = './';
$ignoredDirectory[] = '.';
$ignoredDirectory[] = '..';
if (is_dir($startdir)){
if ($dh = opendir($startdir)){
while (($folder = readdir($dh)) !== false){
if (!(array_search($folder,$ignoredDirectory) > -1)){
if (filetype($startdir . $folder) == "dir"){
$directorylist[$startdir . $folder]['name'] = $folder;
$directorylist[$startdir . $folder]['path'] = $startdir;
}
}
}
closedir($dh);
}
}
return($directorylist);
}
$folders = folderlist();
foreach ($folders as $folder){
$path = $folder['path'];
$name = $folder['name'];
echo '<li><font face="Tahoma" class="ws10"><B>' . $name . '</B><br /></li>';
}
echo "Total Files:". sizeof($folders);
?>