PHP Sort directories by contents - php

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";
}

Related

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);
}
?>

how to work with directory in php

the code is
<?php
$files = array();
$dir = opendir('/xampp/htdocs/myfun/template/home');
while(($file = readdir($dir)) !== false) {
if($file !== '.' && $file !== '..') {
$files[] = $file;
}
}
closedir($dir);
//sort($files);
$i=0;
foreach($files as $key) {
echo "<iframe align='center' width='100%' height='605px' src='$key' title='$files[$i]'></iframe>";
break;
}
?>
i want to show templates onclick next/prev button.horizontally.
like slider.
please help
Correct logic to iterate a directory in while loop is false != ($file = readdir($dir)), where you assign file name first and check it's not false.
Also you can print title with $key itself. $files[$i] and $i variable is not required.
In order to iterate through all files of directory remove break, this will cause to end the loop after first iteration.
<?php
$files = array();
$dir = opendir('/xampp/htdocs/myfun/template/home');
while(false != ($file = readdir($dir)))
{
if($file !== '.' && $file !== '..')
{
$files[] = $file;
}
}
closedir($dir);
//sort($files);
foreach($files as $key)
{
echo "<iframe align='center' width='100%' height='605px' src='$key' title='$key'></iframe>";
}
?>

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.

Sort opendir In Alphabetical Order

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.

Rename all files in a directory with numbers

I was wondering if anyone could help me write a PHP script for me that renames all the files in a directory in a sequence.
So...
DSC_10342.JPG -> 1.JPG
DSC_10343.JPG -> 2.JPG
DSC_10344.JPG -> 3.JPG
and so on.
Here's my version:
// open the current directory (change this to modify where you're looking)
$dir = opendir('.');
$i = 1;
// loop through all the files in the directory
while (false !== ($file = readdir($dir)))
{
// if the extension is '.jpg'
if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'jpg')
{
// do the rename based on the current iteration
$newName = $i . '.jpg';
rename($file, $newName);
// increase for the next loop
$i++;
}
}
// close the directory handle
closedir($dir);
Use rename to rename the files. You can use this handy script to loop through all files in a directory:
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
Then it's just a matter of looking at the filenames ($file) and figuring out what number to give them. If you need more help than that, just tell me and I'll give more details.
Try this:
$handler = opendir($directory);
$index = 1;
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
rename($directory."/".$file, $directory."/".$index.".JPG");
$index++;
}
}
closedir($handler);
Using someone's snippet it would look like this:
<?php
$path = '.';
$i = 1;
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && is_file($path.'/'.$file)) {
$oldname = $path.'/'.$file;
$path_info = pathinfo($oldname);
rename($oldname, $path.'/'.($i++).'.'.$path_info['extension']);
}
}
closedir($handle);
}
?>
It will rename files with all extensions and skip directories that may be inside your directory.

Categories