Sort opendir In Alphabetical Order - php

Is it possible to sort opendir into althabetical order?
$user = $fgmembersite->UserFullName();
$handle = opendir("users/$user/");
while (false!==($file = readdir($handle))) {
if ($file != "." && $file != ".."){
echo 'some code here';
}
}
Thanks in advance!

I would use scandir() instead:
$user = $fgmembersite->UserFullName();
$files = scandir('users/' . $user . '/');
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
// Do stuff here
}
}
As Blauesocke pointed out, it is already sorted.

Related

How can I sort this php directory list by name?

So, simply want my webdrive folder to be "browseable", so I found this script that does it for me.
The problem is, that the list is not sorted by name
How needs the code to be modified so its sorted by filename?
<?php
$dir_open = opendir('.');
while(false !== ($filename = readdir($dir_open))){
if($filename != "." && $filename != ".."){
$link = "<a href='./$filename'> $filename </a><br />";
echo $link;
}
}
closedir($dir_open);
?>
You can store the filenames in an array, then sort them using sort()
$files = [];
$dir_open = opendir('.');
while(false !== ($filename = readdir($dir_open))){
if($filename != "." && $filename != ".."){
$files[] = $filename; // store filename
}
}
closedir($dir_open);
// Then, sort and display
sort($files);
foreach ($files as $filename) {
$link = "<a href='./$filename'> $filename </a><br />";
echo $link;
}

php rename error: The system cannot find the file specified. (code: 2)

<?php
$dir = opendir('C:\Users\Prometheus\Desktop\milkmaid');
$i = 1;
// loop through all the files in the directory
while (false !== ($file = readdir($dir)))
{
if ($file != "." && $file != "..") {
$newName = $i.'.mp4';
$oldname = $file;
rename($oldname, $newName);
$i++;
}
}
?>
when i run above script, i am getting following error:
The system cannot find the file specified. (code: 2)
$dir is not a string. You can't concatenate $file with it. You will need to put the directory in a separate variable, and not forget to put a / in between directory and filename.
Adding $dir in the rename() works for me
<?php
$dir = opendir('C:\Users\Prometheus\Desktop\milkmaid');
$i = 1;
// loop through all the files in the directory
while (false !== ($file = readdir($dir)))
{
if ($file != "." && $file != "..") {
$newName = $i.'.mp4';
$oldname = $file;
rename($dir.$oldname, $dir.$newName);
$i++;
}
}
?>
Use it like this :-
$directory = '/public_html/testfolder/';
$i=1;
if ($handle = opendir($directory)) {
while (false !== ($fileName = readdir($handle))) {
$newName = $i.'.mp4';
rename($directory . $fileName, $directory . $newName);
$i++:
}
closedir($handle);
}
This worked for me
<?php
$counter = 1;
$dir = 'D:\files'; //path of folder
if ($handle = opendir($dir))
{
while (false !== ($fileName = readdir($handle)))
{
if($fileName != '.' && $fileName != '..')
{
$newName = $counter . " - " . $fileName;
rename($dir."/".$fileName, $dir."/".$newName);
$counter++;
}
}
closedir($handle);
}
?>

PHP - Remove '.' and '..' from values fetched from directory files

I am using this code in order to get a list files from directory:
$dir = '/restosnapp_cms/images/';
if ($dp = opendir($_SERVER['DOCUMENT_ROOT'] . $dir)) {
$files = array();
while (($file = readdir($dp)) !== false) {
if (!is_dir($dir . $file)) {
$files[] = $file;
}
}
closedir($dp);
} else {
exit('Directory not opened.');
}
I want to get rid of the values '.' and '..'.
Is it possible to do this? Thank you. :)
Just check for them first:
while ($file = readdir($p)) {
if ($file == '.' || $file == '..') {
continue;
}
// rest of your code
}
DirectoryIterator is much more fun than *dir functions:
$dir = new DirectoryIterator($_SERVER['DOCUMENT_ROOT'] . $dir);
foreach($dir as $file) {
if (!$file->isDir() && !$file->isDot()) {
$files[] = $file->getPathname();
}
}
But the bottomline is regardless of which way you do it, you need to use a conditional.

opendir array exclude file from results

The code below will select all of my php files from the named folder and then shuffle them and echo 10 results on my page, the folder contains an index.php file which i would like to be excluded from the results.
<?php
if ($handle = opendir('../folder/')) {
$fileTab = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$fileTab[] = $file;
}
}
closedir($handle);
shuffle($fileTab);
foreach(array_slice($fileTab, 0, 10) as $file) {
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$thelist .= '<p>'.$title.'</p>';
}
}
?>
<?=$thelist?>
I have found a code to exclude index.php but I'm not sure how to incorporate it into my code above.
<?php
$random = array_values( preg_grep( '/^((?!index.php).)*$/', glob("../folder/*.php") ) );
$answer = $random[mt_rand(0, count($random) -1)];
include ($answer);
?>
Why not just modify the line
if ($file != "." && $file != "..") {
to
if ($file != "." && $file != ".." && $file != 'index.php') {
An approach based on glob() instead of readdir():
<?php
$files = glob('../folder/*.php');
shuffle($files);
$selection = array_slice($files, 0, 11);
foreach ($selection as $file) {
$file = basename($file);
if ($file == 'index.php') continue;
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
// ...
}
You can use
$it = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
$it = new RegexIterator($it, '/.php$/i', RegexIterator::MATCH);
$exclude = array("index.php");
foreach ( $it as $splFileInfo ) {
if (in_array($splFileInfo->getBasename(), $exclude))
continue;
// Do other stuff
}
Or Simply
$files = array_filter(glob(__DIR__ . "/*.php"), function ($v) {
return false === strpos($v, 'index.php');
});
You can exclude it while you reading directory content (like you do with '.' and '..'):
if ($handle = opendir('../folder/')) {
$fileTab = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && $file != "index.php") {
$fileTab[] = $file;
}
}
closedir($handle);
shuffle($fileTab);
foreach(array_slice($fileTab, 0, 10) as $file) {
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$thelist .= '<p>'.$title.'</p>';
}
}
?>
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && $file != 'index.php')
$fileTab[] = $file;
}
you could just change this line if ($file != "." && $file != "..") { to if ($file != "." && $file != ".." && $file != 'index.php') {
The code you found replaces your cumbersome directory reading loop.
And it should be just:
$files = preg_grep('~/index\.php$~', glob("../folder/*.php"), PREG_GREP_INVERT);
Get 10 elements as before:
$files = array_slice($files, 0, 10);
Then output those.

PHP Sort directories by contents

I am trying to sort a list of directories according to the contents of a text file within each directory.
So far, I am displaying the list of directories:
$user = $_GET['user'];
$task_list = $_GET['list'];
if ($handle = opendir("../users/$user/tasks/$task_list/"))
{
$files = array();
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && $file != ".htaccess")
{
array_push($files, $file);
}
}
closedir($handle);
}
//Display tasks
sort($files);
foreach ($files as $file)
{
echo "$file";
}
Each directory has a text file within it called due.txt, I would like to sort the list of directories according to the contents of this file due.txt.
So far, I have tried:
$user = $_GET['user'];
$task_list = $_GET['list'];
if ($handle = opendir("../users/$user/tasks/$task_list/"))
{
$files = array();
$tasksSort = array();
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && $file != ".htaccess")
{
$taskSort = file_get_contents("../users/$user/tasks/$task_list/$file/due.txt");
array_push($files, $file);
array_push($tasksSort, $taskSort);
}
closedir($handle);
}
//Sort tasks and display
sort($tasksSort);
foreach ($files as $file)
{
echo "$file";
}
}
But the $tasksSort array doesn't seem to have any content to sort...?
sort($tasksSort);
foreach ($tasksSort as $file)
{
echo "$file";
}

Categories