Order a directory alphabetically - php

I have some code that prints out the contents of a directory onto a webpage, what seems to be escaping me is how to make it print out alphabetically.
<?php
$dir="../zpress/pages"; // Directory where files are stored
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
if(!is_dir($filename))
{
?>
<p><a href="../zpress/pages/<?php echo $filename; ?>"><?php echo $filename;
?></a></p>
<?php
}
closedir($dir_list);
}
?>
Any suggestion would be most welcome.

You can use scandir which will returns all files in the directory sorted alphabetically
$files = scandir($dir);
foreach($files as $file) {
// your code here
}
scandir

$the_files = array();
while(($filename = readdir($dir_list)) !== false) {
if(!is_dir($filename)) {
array_push($the_files,$filename);
}
}
sort($the_files);
foreach($the_files as $the_file) { ?>
<p><?php echo $the_file;?></p>
<?php } ?>

You can slurp the entire directory list into memory and then apply strnatcasecmp to sort the list:
$dir = ".";
$files = glob("$dir/*");
usort($files, 'strnatcasecmp');
// $files is now sorted
Using strnatcasecmp will give you the order in natural case sort, making for more human-readable output. See here for an explanation: http://sourcefrog.net/projects/natsort/

Related

PHP how to access file from folder and how to download them

<?php
$dir_path = "./folder/";
if(is_dir($dir_path))
{
$files = opendir($dir_path);
{
if($files)
{
while (($file_name = readdir($files)) !== FALSE)
{
if ($file_name != '.' && $file_name != '..'){
echo "".$file_name."<br>";
#echo "<img src=".$file_name.">";
}
}
}
}
}
?>
Returns an array of files and directories from the directory . ... I wanted to easely access data in a certain directory using foreach. I came up with the following:
but it is not download
it say like this
Object not found!
In these cases first you need get files of directory like following:
$dir = './FILE_FOLDER_NAME';
$files = scandir($dir);
unset($files[0]);
unset($files[1]);
Why we used unset, these code remove . and .. from $files variable and you have just file names.
Now you can show files with this approach:
foreach($files as $key => $value):
$path_info = pathinfo($value); //RETURN FILE EXTENTION
?>
<a href="DIRECTORY_PATH<?php echo $value; ?>" target="_blank"><?php echo $value; ?>
<?php
endforeach;
If you want to delete a file can add new button to your foreach like this:
<button href="PHPSAMPLEFILE.PHP?file=<?php echo base64_encode ($value); ?>"><?php echo 'DELETE'; ?></button>
and in your PHP file:
$file = base64_decode($_GET['file']);
$path = './DIRECTORY_PATH/'.$file;
unlink($path);

PHP nested file tree

I have searched on google and on this site for something similar to what I want but nothing fits exactly and all my efforts to adapt them have failed, I want to make a script that will map out its directory and all its subfolders and the folders be at the top of the subdirectory and files after them. So far I have come up with this:
<?php
$rawParent = scandir('.');
$parentDir = array_diff($rawParent, array('.', '..','cgi-bin','error_log'));
$arrayOfDirectories = array();
$arrayOfFiles = array();
foreach ($parentDir as $child){
if(is_dir($child)){
array_push($arrayOfDirectories,$child);
}else{
array_push($arrayOfFiles,$child);
}
}
foreach ($arrayOfDirectories as $directory){
echo $directory.'<br>';
}
echo "<br>";
foreach ($arrayOfFiles as $file){
echo "<a href='".$file."'>".$file.'</a><br>';
}
?>
It's good so far but it only does the first level of the directory, can this code be adapted to go through all levels of folders and nest them? If so how? I need a few pointers, I will further use javascript to have toggles on the folders to see the contents, so I will need PHP to output something nested.
Sorry if I am not making much sense, don't really know how to explain.
Use recursive function like this :
<?php
function list_directory($directory)
{
$the_directory = opendir($directory) or die("Error $directory doesn't exist");
while($file = #readdir($the_directory))
{
if ($file == "." || $file == "..") continue;
if(is_dir($directory.'/'.$file))
{
print '<ul>'.$directory.'/'.$file;
list_directory($directory.'/'.$file);
print '</ul>';
}
else
{
print "<li> $file </li>";
}
}
closedir($the_directory);
}
$path_to_search = '/var/www';
list_directory($path_to_search);
?>
Version with storage in array :
<?php
function list_directory($directory, &$storage)
{
$the_directory = opendir($directory) or die("Error $directory doesn't exist");
while($file = #readdir($the_directory))
{
if ($file == "." || $file == "..") continue;
if(is_dir($directory.'/'.$file))
{
list_directory($directory.'/'.$file, $storage);
}
else
{
$storage[] = $file;
}
}
closedir($the_directory);
}
$storage = array();
$path_to_search = '/var/www';
list_directory($path_to_search, $storage);
echo '<pre>', print_r($storage,true) , '</pre>';
?>
This will do what you asked for, it only returns the sub directory names in a given path, and you can make hyperlinks and use them.
$yourStartingPath = "your string path";
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($yourStartingPath),
RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $file) {
if($file->isDir()) {
$path = strtoupper($file->getRealpath()) ;
$path2 = PHP_EOL;
$path3 = $path.$path2;
$result = end(explode('/', $path3));
echo "<br />". basename($result);
}
}

Sort photos in Php gallery by date

I'm trying to build a gallery for a friend, using PHP. Currently my script imports all the images from a "gallery" folder, and it displays them alphabetically, using automatically generated thumbnails and fancybox plugin.
Is it posible to sort them by date? It doesn't matter if it's the date when they were taken or the date when they were last modified. The code I use is below. Thanks in advance!
<?php
$path = 'gallery/';
$files = scandir('gallery/');
?>
<ul>
<?php foreach ($files as $file){
if ($file == '.' || $file == '..'){
echo '';
} else {
?>
<li><a class="fancybox" rel="group" href="<?php echo $path . $file; ?>"><img src="scripts/timthumb.php?src=<?php echo $path . $file; ?>&h=194&w=224&zc=1&q=100" /></a></li>
<?php } }?>
</ul>
this php function sorts your file by the last date it was modified.
Don't forget to put in the ignored files array which files you want to be ignored.
function scan_dir($dir) {
$ignored_files = array()
$files = array();
foreach (scandir($dir) as $file) {
if (in_array($file,$ignored_files) {
$files[$file] = filemtime($dir.'/'.$file);
}
}
arsort($files);
$files = array_keys($files);
if(is_null($files))
return false;
return $files;
}
You can refactor it a bit this was made really quicly. Hope this will work

how to load images from a directory in a sequence with php?

I have this php code that works great, but the only thing is that images that are loaded from the folder are random, and I need them to load numerically by order.
`
//Open images directory
$dir = opendir("../blogimg/luda_jesus");
//List files in images directoryb
while (($file = readdir($dir)) !== false)
{
if(substr( $file, -3 ) == "jpg" )
{
echo "<div class='container'><img class='lazy' id='background' src='../blogimg/loader.gif' data-original='../blogimg/luda_jesus/" . $file . "' width='884' height='587'></div>";
//echo "<br />";
}
}
closedir($dir);
?>`
Please help me
You can do this much more easily with glob:
$files = glob("../blogimg/luda_jesus/*.jpg");
natsort($files); // can also use other sort functions here, take your pick
foreach ($files as $file) {
echo '...';
}
I chose natsort as the sort function above because it will sort 2.jpg before 10.jpg, while plain sort will do the opposite. See comparison of array sorting functions for more information.
Assuming "numerically" means by filename, you can simply do you while loop and populate all files in an array, sort it, and then load the files.
Example:
//Open images directory
$dir = opendir("../blogimg/luda_jesus");
//List files in images directoryb
while (($file = readdir($dir)) !== false) {
if(substr( $file, -3 ) == "jpg" ) {
$filelist[] = $file;
}
}
closedir($dir);
sort($filelist);
for($i=0; $i<count($filelist)-1; $i++) {
echo "<div class='container'>
<img class='lazy' id='background'
src='../blogimg/loader.gif'
data-original='../blogimg/luda_jesus/" . $file . "'
width='884' height='587'>
</div>";
}
If you require different means of sorting, please mention so.

Convert to array to sort

I have the following code which outputs the contents of text files held in a directory.
Ive been looking at the sort command in PHP but cant get it to work with the following code, I usually get an error about the input being a string and not an array.
How can I sort the directory of file before they are output?
$directory = "polls/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
list($tag, $name, $description, $text1, $text2, $text3, $date) = explode('¬', $contents);
echo '<table width="500" border="1" cellpadding="4">';
echo "<tr><td>$tag</td></tr>\n";
echo "<tr><td>$name</td></tr>\n";
echo "<tr><td>$description</td></tr>\n";
echo "<tr><td>$text1</td></tr>\n";
echo "<tr><td>$text2</td></tr>\n";
echo "<tr><td>$text3</td></tr>\n";
echo "<tr><td>$date</td></tr>\n";
echo '</table>';
}
}
closedir($dir);
First collect the entries in an array, sort it and then put it out:
$directory = "polls/";
$dir = opendir($directory);
$files = array();
while (($file = readdir($dir)) !== false) {
$files[] = $file;
}
closedir($dir);
sort($files);
foreach ($files as $file) {
// content of your original while loop
}
Another possibility is fetching the file names with glob(). Its output is sorted by default.
<?php
foreach(glob('polls/*.txt') as $file){
// ...
}
?>
Don't print it in the while loop, but store it in an array. Sort the array and then print it.
(On php.net you'll find enough different sorting functions to get the sorting method you need.)

Categories