i have a little php script that reads a directory and then echos all the files (jpg's in this case) into a jquery image slider. it works perfectly, but i dont know how to sort the images by name desending. at the moment the images are random.
<?php
$dir = 'images/demo/';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo '<img src="'.$dir.$file.'"/>';
}
closedir($handle);
}
?>
any help on this would be great.
one more thing i dont understand. the script pics up 2 nameless non jpg files in that folder that does not exist??? but i havnt realy checked into that yet
The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.
To check if a folder or a file is in use, the function is_dir() or is_file() can be used. The scandir function is an inbuilt function that returns an array of files and directories of a specific directory. It lists the files and directories present inside the path specified by the user.
The opendir() function opens a directory handle.
Try this:
$dir = 'images/demo/';
$files = scandir($dir);
rsort($files);
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
echo '<img src="' . $dir . $file . '"/>';
}
}
Try putting each item in an array and then sorting that:
$images = array();
while (false !== ($file = readdir($handle))) {
$images[] = $file;
}
natcasesort($images);
foreach ($images as $file) {
echo '<img src="'.$dir.$file.'"/>';
}
asort()
ascending order - arsort()
reverse order
<?php
// You can use the desired folder to check and comment the others.
// foreach (glob("../downloads/*") as $path) { // lists all files in sub-folder called "downloads"
foreach (glob("images/*.jpg") as $path) { // lists all files in folder called "test"
$docs[$path] = filectime($path);
} arsort($docs); // sort by value, preserving keys
foreach ($docs as $path => $timestamp) {
// additional options
// print date("d M. Y: ", $timestamp);
// print '<a href="'. $path .'">'. basename($path) .'</a>' . " Size: " . filesize($path) .'<br />';
echo '<img src="'.$path.$file.'"/><br />';
}
?>
Making use of the glob()
function, you can set the files and folder to your liking.
More on the glob( ) function on PHP.net
To display ALL files, use (glob("folder/*.*")
<?php
foreach (glob("images/*.jpg") as $file) { //change "images" to your folder
if ($file != '.' || $file != '..') {
// display images one beside each other.
// echo '<img src="'.$dir.$file.'"/>';
// display images one underneath each other.
echo '<img src="'.$dir.$file.'"/><br />';
}
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With