Ordering output when using readdir() - php

I'm fairly new to PHP and have been using PHP's readdir() to look into a folder full of images and render them out dynamically based on how many images there are in that folder. Everything works great, but one thing I've noticed is that the images are not displayed in the order that they appear on my local machine HD.
So my question to anyone who knows PHP is, is there way of using PHP to read the contents of a folder AND display them in order without having to rename the actual file names e.g. 01.jpg, 02.jpg etc etc?

Have a look at the glob() function, it returns files alphabetically sorted by default:
$files = glob('/some/path/*.*');
Bonus, you can filter just images, and leave out directories.

readdir likely just takes the file system order. Which is alphabetical on NTFS, but seemingly random on most Unix filesystems. The documentation even says as much: »The entries are returned in the order in which they are stored by the filesystem.«
So you'd have to store the list in an array and sort that based on how you would like them to be sorted.

The php manual says:
string readdir ([ resource $dir_handle ] )
Returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem.
Meaning they should appear the same way.
More information found in the manual.

Why not apply one of the sort-functions of PHP?
$files = readdir( $theFoldersPath );
sort( $files );

Here is what I came up with in answer (together with the help of the people who posted) to my own question.
<?php
$dir = "low res";
$returnstr = "";
// The first part puts all the images into an array, which I can then sort using natsort()
$images = array();
if ($handle = opendir($dir)) {
while ( false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".."){
$images[] = $entry;
}
}
closedir($handle);
}
natsort($images);
print_r($images);
$newArray = array_values($images);
// This bit then outputs all the images in the folder along with it's own name
foreach ($newArray as $key => $value) {
// echo "$key - <strong>$value</strong> <br />";
$returnstr .= '<div class="imgWrapper">';
$returnstr .= '<div class="imgFrame"><img src="'. $dir . '/' . $value . '"/></div>';
$returnstr .= '<div class="imgName">' . $value . '</div>';
$returnstr .= '</div>';
}
echo $returnstr;
?>

Related

While loop, not looping in the correct order

Disclaimer: I did not write this code myself a friend gave it to me.
<?php
$handle = opendir(dirname(realpath(__FILE__)).'/AlgemeneVergaderingen/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<p>' .$file. '</p>';
}
}
?>
The point of this code is to loop inside a map and get all the files and echo them out IN THE ORDER that they are inside of the map.
The code does echo them but not in the correct order.
below 2 pictures to help visualize.
full code/file structure
the actual result
readdir() doesn't guarantee any order. You need to order it yourself.
For reference:
https://utcc.utoronto.ca/~cks/space/blog/unix/ReaddirOrder

PHP help for a beginner. Scanning file structure to return folder names in an array

I am looking for some help with my code, I have looked elsewhere but am having difficulty to really understand what is going on with the code given elsewhere and I am hoping someone can help me.
I have one gallery page that uses $_POST to change the folder the gallery gets it images form based on the link clicked.
What I want now is to code a search function that looks through them all for a string (a jpg) when it finds it, it returns its img tags and displays the image.
I am having trouble making scandir work and display currently using this code
<?php
$dir = "/galleries/images/adult-cakes/images/";
$scan = scandir($dir);
echo $dir;
print_r($scan);
foreach ($scan as $output) {
echo "$output" . "<br />";
}
?>
that returns the echo dir but nothing else ( please note print was something I tried it was echo before and neither is working.
Then I need to get the output of all the gallery types, adult, anniversary etc and put them into a loop like so
search criteria = cake 1(.jpg)
put scandir info into $folderarray
search this folder until found -
galleries/images/$folderarray/images/
loop
if found then echo img tags with link to pic
if not display not found
This will get an array of all the files in directory $dir
<?php
$dir = "/galleries/images/adult-cakes/images/";
$images = glob($dir . '*');
?>
Do this to get all subdirectories of $Dir into array $DirArray:
$Dir = '/galleries/images/'; //
foreach ( $DirArray = array_filter(glob($Dir . '*'), 'is_dir') as $DirName ) {
$DirName = str_replace($Dir, '', $DirName); // Optionally, remove path from name to display
echo "Dir Name: $DirName <br />\n"; // Test
}
echo var_dump($DirArray); // Test
Modify accordingly

Get all files in directory with specified extension with PHP? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP list of specific files in a directory
use php scandir($dir) and get only images!
So right now I have a directory and I am getting a list of files
$dir_f = "whatever/random/";
$files = scandir($dir_f);
That, however, retrieves every file in a directory. How would I retrive only files with a certain extension such as .ini in most efficient way.
PHP has a great function to help you capture only the files you need. Its called glob()
glob - Find pathnames matching a pattern
Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.
Here is an example usage -
$files = glob("/path/to/folder/*.txt");
This will populate the $files variable with a list of all files matching the *.txt pattern in the given path.
Reference -
glob()
If you want more than one extension searched, then preg_grep() is an alternative for filtering:
$files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir_f));
Though glob has a similar extra syntax. This mostly makes sense if you have further conditions, add the ~i flag for case-insensitive, or can filter combined lists.
PHP's glob() function let's you specify a pattern to search for.
You can try using GlobIterator
$iterator = new \GlobIterator(__DIR__ . '/*.txt', FilesystemIterator::KEY_AS_FILENAME);
$array = iterator_to_array($iterator);
var_dump($array);
glob($pattern, $flags)
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
try this
//path to directory to scan
$directory = "../file/";
//get all image files with a .txt extension.
$file= glob($directory . "*.txt ");
//print each file name
foreach($file as $filew)
{
echo $filew;
$files[] = $filew; // to create the array
}
haven't tested the regex but something like this:
if ($handle = opendir('/file/path')) {
while (false !== ($entry = readdir($handle))) {
if (preg_match('/\.txt$/', $entry)) {
echo "$entry\n";
}
}
closedir($handle);
}

How to populate a drop down menu with file names from a directory as options using PHP?

I'm trying to create a drop down menu that points to a directory and populates a drop down menu with the names of certain files in that directory using PHP.
Here's what I'm working with:
<?php
$path = "pages/"; //change this if the script is in a different dir that the files you want
$show = array( '.php', '.html' ); //Type of files to show
$select = "<select name=\"content\" id=\"content\">";
$dh = #opendir( $path );
while( false !== ( $file = readdir( $dh ) ) ){
$ext=substr($file,-4,4);
if(in_array( $ext, $show )){
$select .= "<option value='$path/$file'>$file</option>\n";
}
}
$select .= "</select>";
closedir( $dh );
echo "$select";
?>
This bit of code is giving me an errors, and I'm not even really attached to it if there's a better way of trying to accomplish what I'm trying to do.
It would be easier to use glob() because it can handle wildcards.
// match all files that have either .html or .php extension
$file_matcher = realpath(dirname(__FILE__)) . '/../pages/*.{php,html}';
foreach( glob($file_matcher, GLOB_BRACE) as $file ) {
$file_name = basename($file);
$select .= "<option value='$file'>$file_name</option>\n";
}
You need a full path reference (i.e. /var/www/pages/) instead of just "pages".
Also you might consider using DirectoryIterator object for easily getting to directroy information (if you are using PHP 5).
I don't know, which errors you get. But I think it won't work with the $show array because you're comparing the last 4 chars of the file with the contents of the array. Instead of $ext=substr($file,-4,4); you could write $ext=substr($file, strrpos( $file, ".")); which gives you the string from the position of the last occurance of ".".
Also I suggest for test reason that you omit the # opening the directory because I think that the path cannot be found.

Best way to get files from a dir filtered by certain extension in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP list of specific files in a directory
use php scandir($dir) and get only images!
So right now I have a directory and I am getting a list of files
$dir_f = "whatever/random/";
$files = scandir($dir_f);
That, however, retrieves every file in a directory. How would I retrive only files with a certain extension such as .ini in most efficient way.
PHP has a great function to help you capture only the files you need. Its called glob()
glob - Find pathnames matching a pattern
Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.
Here is an example usage -
$files = glob("/path/to/folder/*.txt");
This will populate the $files variable with a list of all files matching the *.txt pattern in the given path.
Reference -
glob()
If you want more than one extension searched, then preg_grep() is an alternative for filtering:
$files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir_f));
Though glob has a similar extra syntax. This mostly makes sense if you have further conditions, add the ~i flag for case-insensitive, or can filter combined lists.
PHP's glob() function let's you specify a pattern to search for.
You can try using GlobIterator
$iterator = new \GlobIterator(__DIR__ . '/*.txt', FilesystemIterator::KEY_AS_FILENAME);
$array = iterator_to_array($iterator);
var_dump($array);
glob($pattern, $flags)
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
try this
//path to directory to scan
$directory = "../file/";
//get all image files with a .txt extension.
$file= glob($directory . "*.txt ");
//print each file name
foreach($file as $filew)
{
echo $filew;
$files[] = $filew; // to create the array
}
haven't tested the regex but something like this:
if ($handle = opendir('/file/path')) {
while (false !== ($entry = readdir($handle))) {
if (preg_match('/\.txt$/', $entry)) {
echo "$entry\n";
}
}
closedir($handle);
}

Categories