I have this part of script that echos the folders in "albums" folder and arrange them by the alphabet, but for some reason it also includes an empty folder.
$directory = opendir("albums/");
$items = array();
while($items[] = readdir($directory))
sort($items);
closedir($directory);
foreach ($items as $item)
{
if(($item != ".") && ($item != "..")){
$files[] = $item;
}
}
What should I do? I think the if(($item != ".") && ($item != "..")) is part of my problem but I can't figure how to handle it.
The problem is with this line:
while($items[] = readdir($directory))
readdir returns false if no entries are left. That is why you have an extra item in $items
EDIT
while($item = readdir($directory))
{
$items[] = $item;
sort($items);
}
. is the current directory and .. is the parent directory. It's normal that readdir() returns these.
BTW you could simplify your code by using the glob() function:
$files = glob("albums/*");
// that's all
glob("albums/*") will return all entries in the albums directory, sorted alphabetically, and without the dot and dotdot entries.
Try this, as it's in sorted order, just array_shift() twice will do this work. But personally I think it's a kinda hacking...
<?php
$files = array();
foreach (glob('album/*') as $file) {
if (!is_dir($file)) {
$files[] = basename($file);
}
}
sort($files);
You can modify 'album/*' to suit your needs (ex. 'album/*.mp3'). Note that this method is not recursive, so if you need to process subdirectories within the album/ directory, you'll want to modify the code to account for this.
Related
I need to search into folders and subfolders in search for files. In this search I need to know the files names and their path, because I have different folders and files inside of those.
I have this name 05-Navy, and inside this folder I have 3 files called 05_Navy_White_BaseColor.jpg, 05_Navy_White_Normal.jpg and 05_Navy_White_OcclusionRoughnessMetallic.jpg.
I need to only get one of them at a time because I need to add they separately to different lists.
Then I came up with the code below:
function getDirContents($dir, &$results = array()) {
$files = scandir($dir);
$findme = '_BaseColor';
$mypathCordas = null;
$findmeCordas = 'Cordas';
foreach ($files as $key => $value) {
$path = realpath($dir . DIRECTORY_SEPARATOR . $value);
$mypathCordas = $path;
$pos = strpos($mypathCordas, $findme);
$posCordas = strpos($mypathCordas, $findmeCordas);
if (!is_dir($path)) {
if($posCordas == true){
if($pos == true){
$results[] = $path;
}
}
}
else if ($value != "." && $value != ".." ) {
if($posCordas == true){
echo "</br>";
getDirContents($path, $results);
//$results[] = $path;
}
}
}
sort( $results );
for($i = 0; $i < count($results); $i++){
echo $results[$i];
echo "</br>";
}
return $results;
}
getDirContents('scenes/Texturas');
as output result I get this: Results1
Which is not ideal at all, the biggest problem is that the list inserts the same values every time it has do add new ones, and as you can see, it doesn't sort one bit, but it shuffles. I did other things, like I have tried to use DirectoryIterator which worked really well, but I couldn't sort at all...
The printing each time something new is on the list might be my for(), but I am relatively new to php, so I can't be sure.
Also, there's this thing where it gets all the path, and I already tried using other methods but got only errors, where I would only need the scenes/texturas/ instead of the absolute path....
I use this code to list all files in directory:
$d = dir($FolderToPlay);
while (($file = $d->read()) !== false){
...
...
}
$d->close();
But, the result is not in the numerical order. How can I fix it?
Get a list of all the filenames, then you can use a sorting function.
$d = glob("$FolderToPlay/*");
natsort($d);
foreach ($d as $file) {
...
}
The easiest way to list all files in a directory is with scarndir() fuction.
You can use it like this:
//Create a variable that contains all your files
$root = scandir($dir);
//Do something with each value, like push them into an array, do regex etc.
foreach($root as $value){
//...
}
I'm working on an IMDB style website and I need to dynamically find the amount of reviews for a movie. The reviews are stored in a folder called /moviefiles/moviename/review[*].txt where the [*] is the number that the review is. Basically I need to return as an integer how many of those files exist in that directory. How do I do this?
Thanks.
Use php DirectoryIterator or FileSystemIterator:
$directory = new DirectoryIterator(__DIR__);
$num = 0;
foreach ($directory as $fileinfo) {
if ($fileinfo->isFile()) {
if($fileinfo->getExtension() == 'txt')
$num++;
}
}
Take a look at the glob() function: http://php.net/manual/de/function.glob.php
You can then use sizeof() to count how many files there are.
First, use glob () to get file list array, then use count () to get array length, the array length is file count.
Simplify code:
$txtFileCount = count( glob('/moviefiles/moviename/review*.txt') );
You can use this php code to get the number of text files in a folder
<div id="header">
<?php
// integer starts at 0 before counting
$i = 0;
$dir = 'folder-path';
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
{
$temp = explode(".",$file);
if($temp[1]=="txt")
$i++;
}
}
}
// prints out how many were in the directory
echo "There were $i files";
?>
</div>
This is a very simple code that works well. :)
$files = glob('yourfolder/*.{txt}', GLOB_BRACE);
foreach($files as $file) {
your work
}
So, I'm familiar with Javascript, HTML, and Python. I have never learned PHP, and at the moment, I'm banging my head against my desk trying to figure out what (to me) seems to be such a simple thing.
I have a folder, with other folders, that contain images.
At the moment, I'm literally just trying to get a list of the folders as links. I get kind of there, but then my output is always reversed! Folder01, Folder02 comes out as Folder02, Folder01. I can't fricken' sort my output. I've been searching constantly trying to figure this out but nothing is working for me.
<?php
function listAlbums(){
if ($handle = opendir('./photos/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo $entry . "<br/>";
}
}
closedir($handle);
}
}
?>
This outputs: Folder02, Folder01. I need it the other way around. I've tried asort, array_reverse, etc. but I must not be using them properly. This is killing me. I never had to even thin about this in Python, or Javascript, unless I actually wanted to have an ascending list...
Try one of these, one is recursive, one is not:
// Recursive
function listAlbums($path = './photos/')
{
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
foreach($objects as $name => $object) {
ob_start();
echo rtrim($object,".");
$data = ob_get_contents();
ob_end_clean();
$arr[] = $data;
}
return array_unique($arr);
}
// Non-recursive
function getAlbums($path = './photos/')
{
$objects = dir($path);
while (false !== ($entry = $objects->read())) {
if($entry !== '.' && $entry !== '..')
$arr[] = $path.$entry;
}
$objects->close();
return $arr;
}
// I would use __DIR__, but not necessary
$arr = listAlbums();
$arr2 = getAlbums();
// Reverse arrays by key
krsort($arr);
krsort($arr2);
// Show arrays
print_r($arr);
print_r($arr2);
I try your code and make simple changes and I am able to do what you want to get.
Here is my code ( copy of your code + Modify ) :
function listAlbums() {
$files = array();
if ($handle = opendir('./photos/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
//echo $entry . "<br/>";
$files[] = $entry;
}
}
closedir($handle);
}
// Sort your folder in ascending order
sort($files);
// Sort your folder in descending order [ code commented ]
//rsort($files);
// Check your photos folder has folder or not
if( !empty( $files ) ) {
// Show Your Folders
foreach ($files as $key => $folderName ) {
echo $folderName . "<br/>";
}
} else {
echo 'You have no folder yet in photos directory';
}
}
My Changes:
First store your all folders in the photos directory in an array variable
Secondly sort this array whatever order you want.
Finally show your folders (And your work will be solved)
You can know more about this from sort-and-display-directory-list-alphabetically-using-opendir-in-php
Thanks
Ok, this is the best result i've gotten all night. This does 99% of what I need. But I still can't figure out this damn sort issue. This code will go through a list of directories, and create lightbox galleries out of the images in each folder. However, the first image is always the last one in the array, and I can't figure out how the heck to get it to sort normally! Check line 16 to see where I talking about.
<?php
function listAlbums(){
$directory = "./photos/";
//get all folders in specified directory
$folders = glob($directory . "*");
//get each folder item name
foreach($folders as $folderItem){
//check to see if the folderItem is a folder/directory
if(is_dir($folderItem)){
$count = 0;
foreach (new DirectoryIterator($folderItem) as $fileInfo) {
if($fileInfo->isDot()) continue;
$files = $folderItem."/".$fileInfo->getFilename();
if ($count == 0){ //This is where my issues start. This file ends up being the last one in the list. I need it to be the first.
echo ''.basename($folderItem).'' . "<br/>";
echo "<div style='display: none'>" . "<br/>";
$count++;
}else{
echo ''.basename($folderItem).'' . "<br/>";
}
}echo "</div>";
}
}
}
?>
Whew! Ok, I got everything working. DirectoryIterator was pissing me off with its random print order. So I fell back to just glob and scandir. Those seem to print out a list "logically". To summarize, this bit of php will grab folders of images and turn each folder into its own lightbox gallery. Each gallery shows up as a hyperlink that triggers the lightbox gallery. I'm pretty happy with it!
So here's my final code:
<?php
function listAlbums(){
$directory = "./photos/";
//get all folders in specified directory
$folders = glob($directory . "*");
//get each folder item name
foreach($folders as $folderItem){
//check to see if the folderItem is a folder/directory
if(is_dir($folderItem)){
$count = 0;
$scanDir = scandir($folderItem);
foreach($scanDir as $file){
if ($file === '.' || $file === '..') continue;
$filePath = $folderItem."/".$file;
if ($count == 0){
echo ''.basename($folderItem).'' . "<br/>";
echo "<div style='display: none'>" . "<br/>";
$count++;
}else{
echo ''.basename($folderItem).'' . "<br/>";
}
}echo "</div>";
}
}
}
Special thanks to Rasclatt for bearing with me through all of this and offering up a lot of hand-holding and help. I really appreciate it!
I have the following function that enumerates files and directories in a given folder. It works fine for doing subfolders, but for some reason, it doesn't want to work on a parent directory. Any ideas why? I imagine it might be something with PHP's settings or something, but I don't know where to begin. If it is, I'm out of luck since this is will be running on a cheap shared hosting setup.
Here's how you use the function. The first parameter is the path to enumerate, and the second parameter is a list of filters to be ignored. I've tried passing the full path as listed below. I've tried passing just .., ./.. and realpath('..'). Nothing seems to work. I know the function isn't silently failing somehow. If I manually add a directory to the dirs array, I get a value returned.
$projFolder = '/hsphere/local/home/customerid/sitename/foldertoindex';
$items = enumerateDirs($projFolder, array(0 => "Admin", 1 => "inc"));
Here's the function itself
function enumerateDirs($directory, $filterList)
{
$handle = opendir($directory);
while (false !== ($item = readdir($handle)))
{
if ($item != "." && $item != ".." && $item != "inc" && array_search($item, $filterList) === false)
{
$path = "{$directory->path}/{$item}";
if (is_dir($item))
{
$tmp['name'] = $item;
$dirs[$item] = $tmp;
unset($tmp);
}
elseif (is_file($item))
{
$tmp['name'] = $item;
$files[] = $tmp;
unset($tmp);
}
}
}
ksort($dirs, SORT_STRING);
sort($dirs);
ksort($files, SORT_STRING);
sort($files);
return array("dirs" => $dirs, "files" => $files);
}
You are mixing up opendir and dir. You also need to pass the full path (including the directory component) to is_dir and is_file. (I assume that's what you meant to do with $path.) Otherwise, the functions will look for the corresponding file system objects in the script file's directory.
Try this for a quick fix:
<?php
function enumerateDirs($directory, $filterList)
{
$handle = dir($directory);
while (false !== ($item = $handle->read()))
{
if ($item != "." && $item != ".." && $item != "inc" && array_search($item, $filterList) === false)
{
$path = "{$handle->path}/{$item}";
$tmp['name'] = $item;
if (is_dir($path))
{
$dirs[] = $tmp;
}
elseif (is_file($path))
{
$files[] = $tmp;
}
unset($tmp);
}
}
$handle->close();
/* Anonymous functions will need PHP 5.3+. If your version is older, take a
* look at create_function
*/
$sortFunc = function ($a, $b) { return strcmp($a['name'], $b['name']); };
usort($dirs, $sortFunc);
usort($files, $sortFunc);
return array("dirs" => $dirs, "files" => $files);
}
$ret = enumerateDirs('../', array());
var_dump($ret);
Note: $files or $dirs might be not set after the while loop. (There might be no files or directories.) In that case, usort will throw an error. You should check for that in some way.