Looping through directory backwards - php

Hay all im using a simple look to get file names from a dir
if ($handle = opendir('news_items/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
}
}
}
the files are being outputted news last, oldest first.
How can i reverse this so the newest files are first?

Get the file list into an array, then array_reverse() it :)

the simplest option is to invoke a shell command
$files = explode("\n", `ls -1t`);
if, for some reason, this doesn't work, try glob() + sort()
$files = glob("*");
usort($files, create_function('$a, $b', 'return filemtime($b) - filemtime($a);'));

Pushing every files in an array whit mtime as key allow you to reverse sort that array:
<?php
$files = array();
if ($handle = opendir('news_items/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$mtime = filemtime('news_items/' . $file);
if (!is_array($files[$mtime])) {
$files[$mtime] = array();
}
array_push($files[$mtime], $file);
}
}
}
krsort($files);
foreach ($files as $mt=>$fi) {
sort($fi);
echo date ("F d Y H:i:s.", $mt) . " : " . implode($fi, ', ') . "\n";
}
?>

Related

Array of file names needs sorting [duplicate]

I'm using the following PHP code to list all files and folders under the current directory:
<?php
$dirname = ".";
$dir = opendir($dirname);
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != "..") and ($file != "index.php"))
{
echo("<a href='$file'>$file</a> <br />");
}
}
?>
The problem is list is not ordered alphabetically (perhaps it's sorted by creation date? I'm not sure).
How can I make sure it's sorted alphabetically?
The manual clearly says that:
readdir
Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.
What you can do is store the files in an array, sort it and then print it's contents as:
$files = array();
$dir = opendir('.'); // open the cwd..also do an err check.
while(false != ($file = readdir($dir))) {
if(($file != ".") and ($file != "..") and ($file != "index.php")) {
$files[] = $file; // put in array.
}
}
natsort($files); // sort.
// print.
foreach($files as $file) {
echo("<a href='$file'>$file</a> <br />\n");
}
<?php
function getFiles(){
$files=array();
if($dir=opendir('.')){
while($file=readdir($dir)){
if($file!='.' && $file!='..' && $file!=basename(__FILE__)){
$files[]=$file;
}
}
closedir($dir);
}
natsort($files); //sort
return $files;
}
?>
<html>
<head>
</head>
<body>
<h1> List of files </h1>
<ul class="dir">
<? foreach(getFiles() as $file)
echo "<li name='$file'><a href='$file'>$file</a></li>";
?>
</ul>
</body>
</html>
Using glob and sort it should work.
You could put all the directory names inside an array like:
$array[] = $file;
After that you can sort the array with:
sort($array);
And then print the links with that content.
I hope this help.
<?php
$dirname = ".";
$dir = opendir($dirname);
while(false != ($file = readdir($dir)))
{
if(($file != ".") and ($file != "..") and ($file != "index.php"))
{
$list[] = $file;
}
}
sort($list);
foreach($list as $item) {
echo("<a href='$item'>$item</a> <br />");
}
?>
I'd recommend moving away from the old opendir()/readdir(). Either use glob() or if you encounter a lot of files in a directory then use the DirectoryIterator Class(es):
http://www.php.net/manual/en/class.directoryiterator.php
http://www.php.net/manual/en/function.glob.php
Regards
You can use this beautiful script:
http://halgatewood.com/free-php-list-files-in-a-directory-script/

Display files in a folder along with the date modified of those files

<?php
$filename = 'file:///C:/Users/xxx/Desktop/2017/cdr'
$files = array();
if ($handle = opendir($filename)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files[filemtime($file)] = $file;
}
}
closedir($handle);
// sort
ksort($files);
// find the last modification
$reallyLastModified = end($files);
foreach($files as $file) {
$lastModified = date('F d Y, H:i:s',filemtime($file));
if(strlen($file)-strpos($file,".swf")== 4){
if ($file == $reallyLastModified) {
// do stuff for the real last modified file
}
echo "<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td>$file</td><td>$lastModified</td></tr>";
}
}
}
I have been trying to use this code to list and show files in a folder along with the date modified. i keep getting an error filemtime(): stat failed.
İ am trying listing them as arrays as an alternative using the below code
<?php
$folder = 'file:///C:/Users/xxx/Desktop/2017/cdr';
$backups = array();
foreach (scandir($folder) as $node) {
$nodePath = $folder . DIRECTORY_SEPARATOR . $node;
if (is_dir($nodePath)) continue;
$backups[$nodePath] = filemtime($nodePath);
}
ksort($backups);
print_r($backups);
when i run this code i get the result below and i dont know what the numbers represent.
[file:///C:/Users/xxx/Desktop/2017/cdr\2017_0622_1500.raw] =>1498136278
[file:///C:/Users/xxx/Desktop/2017/cdr\2017_0622_1600.cdr] =>1498136430
[file:///C:/Users/xxx/Desktop/2017/cdr\2017_0622_1600.raw] =>1498139955
[file:///C:/Users/xxx/Desktop/2017/cdr\2017_0622_1700.raw] =>1498142424
what am trying to achieve is to be able to display the files in the CDR along with their modified dates.
<?php
function cmp($a, $b) {
if (filemtime($a) == filemtime($b))
return 0;
return (filemtime($a) < filemtime($b)) ? -1 : 1;
}
$files = glob("/Users/xxx/Desktop/2017/cdr/*.cdr");
usort($files, "cmp");
foreach($files as $file)
//echo $file . "<br />";
echo "$file was last modified: " . date ("d-m-Y H:i:s.", filemtime($file))."\n";
?>
This seemed to work. And the out put looked like this.
/2017/cdr/2017_0330_1300.cdr last modified: 30-03-2017 10:53:23.
/2017/cdr/2017_0330_1500.cdr last modified: 30-03-2017 12:18:05.
/2017/cdr/2017_0330_1600.cdr last modified:30-03-2017 13:55:21.

Cannot sort the results of this php script descending

Hello I suspect I am being silly but I am new to PHP coding. All I want to do is sort my results from this script below in a descending order, but I don't know what code to add and where to add it. Please can you help me with this.
<?php
$d = dir("01-Newsletters");
while (false != ($entry = $d->read())) {
if ($entry != "." && $entry != "..") {
echo "<tr><td>{$entry}</td><td><a href='01-Newsletters/{$entry}' target=_blank><img src='../../Site_data/Images/more.gif'/></a></td></tr>";}
}
$d->close();
?>
Currently it is giving this result
Previous Newsletters 2014-04-Newsletter.pdf
2014-07-Newsletter.pdf
2014-10-Newsletter.pdf
2015-01-Newsletter.pdf
2015-04-Newsletter.pdf
2015-08-Newsletter.pdf
You can use the following solution:
<?php
$d = dir("01-Newsletters");
$entries = [];
while (false != ($entry = $d->read())) {
if ($entry != "." && $entry != "..") {
$entries[] = $entry;
}
}
$d->close();
//order the entries...
sort($entries, SORT_STRING);
$entries = array_reverse($entries);
//output the $entries in DESC order...
for ($i = 0; $i < count($entries); $i++) {
echo "<tr><td>{$entries[$i]}</td><td><a href='01-Newsletters/{$entries[$i]}' target=_blank><img src='../../Site_data/Images/more.gif'/></a></td></tr>";
}
?>
if the folder name is 2015-8 I assume it is created on that particular day. On the basis of this assumption, you can use the following approach. Get files modified time store it in an array and then sort that array
$dir = "jays";
$d = dir($dir);
while (false != ($entry = $d->read()))
{
if ($entry != "." && $entry != "..")
{
$files[$entry] = filemtime( $dir.'/' . $entry);
}
}
arsort($files);
print_r($files);
$d->close();

Sort by date in descending order echoed file directory in PHP

Ok I have a directory with files named by date with the extension ".html".
What I am trying to do is list the contents of the directory, minus the file extension, ordered by date with newest on top.
I have been fiddling with the below code for hours.
<?php
if ($handle = opendir('update_table_cache')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." ) {
$dirFiles[] = $entry ;
rsort($dirFiles);
foreach($dirFiles as $entry) {
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $entry);
echo ''.$withoutExt.'<br>';
}
}
}
closedir($handle);
}
?>
This outputs something like this:
2016-01-18
2016-01-19
2016-01-18
There should only be one 2016-01-18 and it should be at the bottom. Why is there an extra 2016-01-18 at the top?
Edit: ok I changed it to the following:
<?php
if ($handle = opendir('update_table_cache')) {
$dirFiles[] = $entry ;
rsort($dirFiles);
foreach($dirFiles as $entry) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." ) {
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $entry);
echo ''.$withoutExt.'<br>';
}
}
}
closedir($handle);
}
?>
But this outputs:
2016-01-18
2016-01-17
2016-01-19
(I added another file "2016-01-17.html")
You're doing the output in the middle of the loop...
First you sort one element and print it, then sort two elements and print it.
Do the output after the loop.
This is what worked:
<?php
$dir = opendir('update_table_cache'); // Open the sucker
$files = array();
while ($files[] = readdir($dir));
sort($files);
closedir($dir);
foreach ($files as $file) {
//MANIPULATE FILENAME HERE, YOU HAVE $file...
if ($file != "." && $file != ".." ){
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file);
echo ''.$withoutExt.'<br>';
}
}
?>
Thanks to user CBroe for pointing me in the right direction!

Php list files in a directory and remove extention

I use this php code to retrieve the files stored in a directory .
if ($handle = opendir('FolderPath')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n <br />" ;
}
}
closedir($handle);
}
This Directory only holds PHP files , how would i be able to remove the extension from the echoed results? example: ( index.php would become index )
The easiest way to do this is by using the glob function:
foreach (glob('path/to/files/*.php') as $fileName) {
//extension .php is guaranteed here
echo substr($fileName, 0, -4), PHP_EOL;
}
The advantages of glob here is that you can do away with those pesky readdir and opendir calls. The only slight "disatvantage" is that the value of $fileName will contain the path, too. However, that's an easy fix (just add one line):
foreach (glob('path/to/files/*.php') as $fullName) {
$fileName = explode('/', $fullName);
echo substr(
end($fileName),//the last value in the array is the file name
0, -4),
PHP_EOL;
}
This should work for you:
echo basename($entry, ".php") . "\n <br />" ;
A quick way to do this is
<?php
if ($handle = opendir('FolderPath')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$info = pathinfo($file);
$file_name = basename($file,'.'.$info['extension']);
echo $file_name;
}
}
closedir($handle);
?>
$files = glob('path/to/files/*.*');
foreach($files as $file) {
if (! is_dir($file)) {
$file = pathinfo($file);
echo "<br/>".$file['filename'];
}
}
Use pathinfo()
$entry = substr($entry, 0, strlen($entry) - 4);
Note that this is a simple and quick solution which works perfect if you are 100% sure that your extension is in the form of *.xxx. However if you need a more flexible and safer solution regarding possible different extension lenghts, than this solution is not recommended.
Elegant solution would be to use $suffix attribute of DirectoryIterator::getBasename() method. When provided, $suffix will be removed on each call. For known extension, you can use:
foreach (new DirectoryIterator('/full/dir/path') as $file) {
if ($file->isFile()) {
print $file->getBasename('.php') . "\n";
}
}
or this, as an universal solution:
foreach (new DirectoryIterator('/full/dir/path') as $file) {
if ($file->isFile()) {
print $file->getBasename($file->getExtension() ? '.' . $file->getExtension() : null) . "\n";
}
}
PHP docs: http://php.net/manual/en/directoryiterator.getbasename.php

Categories