I'm in the process of creating an experiment for a psychology researcher, there are various tasks involved which the participant has to complete. I have been asked to randomise the order of the folders, but keep the order of files inside the directories the same.
I have looked at using glob() but I think I'm implementing it wrong.
My directory looks like this:
Clock
>>Task 1/Files.>>Task 2/Files.>>Task 3/Files.
At the moment I have this:
<?php
function random_folders($dir = 'Clock')
{
$folder = glob($dir. '/Task.*');
$folderRand = array_rand($folder);
return $folder[$folderRand];
}
echo random_folders();
?>
I've tried googling and using stackoverflow to search for a solution but I can't seem to find one, any help will be greatly appreciated.
Edit
I should mention that I'm using HTML5, JavaScript, PHP and MySQL to create the website, if that's relevant.
Thanks.
Your glob() is a little off. You don't want the . before the *. Then use shuffle() to shuffle them:
function random_folders($dir = 'Clock')
{
$folder = glob($dir. '/Task*');
shuffle($folder);
// Returns the randomized array of folders
return $folder;
}
$random_folders = random_folders();
// List them and their contents:
foreach ($random_folders as $rf) {
echo "Folder: $rf\n";
// List files in ascending order
$files = scandir($rf, SCANDIR_SORT_ASCENDING);
foreach ($files as $f) {
if ($file !== "." && $file !== "..") {
echo $file . "\n";
}
}
Related
i'm looking for away to see if the query 'id' has a folder with the same id as name in the file system, i did it but it will slow down the drive in the future with lots of files
$query = Model::all();
if(Input::get('field') == 'true'){
$filenames = scandir('img/folders');
$query->whereIn('id', $filenames);
}
as you can see this will scan and get names of all folders inside the 'folders' directory and create an array with it, now my app is going to have hundreds of thousands of folders in the future and i would like to resolve it before it happens, thanks for further help
ps: other propositions to do it differently are welcome
Do you have good reason to believe that scandir on a directory with a large number of folders will actually slow you down?
You can do your query like this:
if(Input::has('field')){
$filenames = scandir('img/folders');
$query = Model::whereIn('id', $filenames)->get();
}
Edit 1
You may find these links useful:
PHP: scandir() is too slow
Get the Files inside a directory
Edit 2
There are some really good suggestions in the links which you should be able to use for guidance to make your own implementation. As I see it, based on the links included from the first edit I made, your options are use DirectoryIterator, readdir or chunking with scandir.
This is a very basic way of doing it but I guess you could do something with readdir like this:
$ids = Model::lists('id');
$matches = [];
if($handle = opendir('path/to/folders'))
{
while (($entry = readdir($handle)) !== false)
{
if(count($ids) === 0)
{
break;
}
if ($entry != "." && $entry != "..")
{
foreach ($ids as $key => $value)
{
if($value === $entry)
{
$matches[] = $entry;
unset($ids[$key]);
}
}
}
}
closedir($handle);
}
return $matches;
(Well what I gone through a lot of posts here on stackoverflow and other sites. I need a simple task, )
I want to provide my user facility to click on upload file from his account, then select a directory and get the list of all the files names inside that directory.
According to the posts here what I got is I have to pre-define the directory name, which I want to avoid.
Is there a simple way to click a directory and get all the files names in an array in PHP? many thanks in advance!
$dir = isset($_POST['uploadFile']) ? _SERVER['DOCUMENT_ROOT'].'/'.$_POST['uploadFile'] : null;
if ($_POST['uploadFile'] == true)
{
foreach (glob($dir."/*.mp3") as $filename) {
echo $filename;
}
}
I will go ahead and post a sample of code I am currently using, with a few changes, although I would normally tell you to look it up on google and try it first.
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
echo $file;
}
closedir($handle);
}
This will display the entire contents of a directory... including: ".", "..", any sub-directories, and any hidden files. I am sure you can figure out a way to hide those if it is not desirable.
<?php
$files=glob("somefolder/*.*");
print_r($files);
?>
Take a look at the Directory class (here) and readdir()
I'm confused what do you want, all files or only some files?
But if you want array of folders and files, do this
$folders = array();
$files = array();
$dir = opendir("path");
for($i=0;false !== ($file = readdir($dir));$i++){
if($file != "." and $file != ".."){
if(is_file($file)
$files[] = $file;
else
$folders[] = $file;
}
}
And if only some folders you want, later you can delete them from array
I always use this amazing code to get file lists:
$THE_PATTERN=$_SERVER["DOCUMENT_ROOT"]."/foldername/*.jpg";
$TheFilesList = #glob($THE_PATTERN);
$TheFilesTotal = #count($TheFilesList);
$TheFilesTotal = $TheFilesTotal - 1;
$TheFileTemp = "";
for ($TheFilex=0; $TheFilex<=$TheFilesTotal; $TheFilex++)
{
$TheFileTemp = $TheFilesList[$TheFilex];
echo $TheFileTemp . "<br>"; // here you can get full address of files (one by one)
}
I need to get all the folders and files from a folder recursively in alphabetical order (folders first, files after)
Is there an implemented PHP function which caters for this?
I have this function:
function dir_tree($dir) {
$path = '';
$stack[] = $dir;
while ($stack) {
$thisdir = array_pop($stack);
if ($dircont = scandir($thisdir)) {
$i=0;
while (isset($dircont[$i])) {
if ($dircont[$i] !== '.' && $dircont[$i] !== '..' && $dircont[$i] !== '.svn') {
$current_file = "{$thisdir}/{$dircont[$i]}";
if (is_file($current_file)) {
$path[] = "{$thisdir}/{$dircont[$i]}";
} elseif (is_dir($current_file)) {
$path[] = "{$thisdir}/{$dircont[$i]}";
$stack[] = $current_file;
}
}
$i++;
}
}
}
return $path;
}
I have sorted the array and printed it like so:
$filesArray = dir_tree("myDir");
natsort($filesArray);
foreach ($filesArray as $file) {
echo "$file<br/>";
}
What I need is to know when a new sub directory is found, so I can add some spaces to print it in a directory like structure instead of just a list.
Any help?
Many thanks
Look at the RecursiveDirectoryIterator.
$directory_iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
foreach($directory_iterator as $filename => $path_object)
{
echo $filename;
}
I'm not sure though if it returns the files in alphabetical order.
Edit:
As you say it does not, I think the only way is to sort them yourself.
I would loop through each directory and put directories and files in a seperate arrays, and then sort them, and then recurse in the directories.
I found a link which helped me a lot in what I was trying to achieve:
http://snippets.dzone.com/posts/show/1917
This might help someone else, it creates a list with folders first, files after. When you click on a subfolder, it submits and another page with the folders and files in the partent folder is generated.
The following code loads all .php files found in the specified folder (defined separately). Is there a way to put this into an array to simplify the code?
Only a couple of variables change but essentially the code repeats several times.
// The General Files
$the_general = opendir(FRAMEWORK_GENERAL);
while (($the_general_files = readdir($the_general)) !== false) {
if(strpos($the_general_files,'.php')) {
include_once(FRAMEWORK_GENERAL . $the_general_files);
}
}
closedir($the_general);
// The Plugin Files
$the_plugins = opendir(FRAMEWORK_PLUGINS);
while (($the_plugins_files = readdir($the_plugins)) !== false) {
if(strpos($the_plugins_files,'.php')) {
include_once(FRAMEWORK_PLUGINS . $the_plugins_files);
}
}
closedir($the_plugins);
There are several more sections which call different folders.
Any help is greatly appreciated.
Cheers,
James
I nicer way to do this would to use glob(). And make it into a function.
function includeAllInDirectory($directory)
{
if (!is_dir($directory)) {
return false;
}
// Make sure to add a trailing slash
$directory = rtrim($directory, '/\\') . '/';
foreach (glob("{$directory}*.php") as $filename) {
require_once($directory . $filename);
}
return true;
}
This is fairly simple. See arrays and foreach.
$dirs = array(FRAMEWORK_GENERAL, FRAMEWORK_PLUGINS, );
foreach ($dirs as $dir) {
$d = opendir($dir);
while (($file = readdir($d)) !== false) {
if(strpos($file,'.php')) {
include_once($dir . $file);
}
}
closedir($d);
}
A better idea might be lazy loading via __autoload or spl_autoload_register, including all the .php files in a directory might seem like a good idea now, but not when your codebase gets bigger.
Your code should be layed out in an easy to understand heirarchy, rather than putting them all in one directory so they can be included easily. Also, if you dont need all of the code in the files in every request you are wasting resources.
Check http://php.net/manual/en/language.oop5.autoload.php for an easy example.
This can be done pretty tightly:
$dirs = array(FRAMEWORK_GENERAL, FRAMEWORK_PLUGINS);
foreach($dirs as $dir) {
if (!is_dir($dir)) { continue; }
foreach (glob("$dir/*.php") as $filename) {
include($filename);
}
}
Put that in a function where $dirs comes in as a param and use freely.
I'm not sure how simple this would be, but I'm using a script which displays the files from a specific folder, however I'd like them to be displayed in alphabetical order, would it be hard to do this? Here's the code I'm using:
if ($handle = opendir($mainframe->getCfg( 'absolute_path' ) ."/images/store/")) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if (($file != "index.html")&&($file != "index.php")&&($file != "Thumbs.db")) {
$strExt = end(explode(".", $file));
if ($strExt == 'jpg') {
$Link = 'index.php?option=com_shop&task=deleteFile&file[]='.$file;
$thelist .= '<tr class="row0"><td nowrap="nowrap">'.$file.'</td>'."\n";
$thelist .= '<td align="center" class="order"><img src="/administrator/images/publish_x.png" width="16" height="16" alt="delete"></td></tr>'."\n";
}
}
}
}
closedir($handle);
}
echo $thelist;
:)
Instead of using readdir you could simply use scandir (documentation) which sorts alphabetically by default.
The return value of scandir is an array instead of a string, so your code would have to be adjusted slightly, to iterate over the array instead of checking for the final null return value. Also, scandir takes a string with the directory path instead of a file handle as input, the new version would look something like this:
foreach(scandir($mainframe->getCfg( 'absolute_path' ) ."/images/store/") as $file) {
// rest of the loop could remain unchanged
}
That code looks pretty messy. You can separate the directory traversing logic with the presentation. A much more concise version (in my opinion):
<?php
// Head of page
$it = new DirectoryIterator($mainframe->getCfg('absolute_path') . '/images/store/'));
foreach ($it as $file) {
if (preg_match('#\.jpe?g$#', $file->getFilename()))
$files[] = $file->getFilename();
}
sort($files);
// Further down
foreach ($files as $file)
// display links to delete file.
?>
You don't even need to worry about opening or closing the handle, and since you're checking the filename with a regular expression, you don't need any of the explode or conditional checks.
I like Glob
It makes directory reading a snap as it returns an array that's easily sortable:
<?php
$files = glob("*.txt");
sort($files);
foreach ($files as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
If you're using Joomla1.5 you should be using the defined constant JPATH_BASE instead of
$mainframe->getCfg( 'absolute_path' )
If this is a Joomla extension that you will distribute, don't use scandir() as it is PHP5 only.
The best thing to do is to use the Joomla API. It has a classes for directory and file access that is layered to do this over different networks and protocols. So the file system can be over FTP for example, and the classes can be extended for any network/protocol.
jimport( 'joomla.filesystem.folder' );
$files = JFolder::files(JPATH_BASE."/images/store/");
sort($files);
foreach($files as $file) {
// do your filtering and other task
}
You can also pass a regular expression as the second parameter to JFolder::files() that filters the files you receive.
You also don't want to use URL literals like /administrator/ since they can be changed.
use the JURI methods like:
JURI::base();
If you want to make sure of the Joomla CSS classes in the tables, for:
'<tr class="row0">'
use:
'<tr class="row'.($i&1).'">'
where $i is the number of iterations. This gives you a sequence of alternating 0s and 1s.
if we have PHP built in functions, always use it, they are faster.
use glob instead of traversing folders, if it fits for your needs.
$folder_names = array();
$folder_names = glob( '*', GLOB_ONLYDIR + GLOB_MARK + GLOB_NOSORT );
returs everything in the current directory, use chdir() before calling it
remove the GLOB_ONLYDIR to include files too ( . would be only files )
GLOB_MARK is for adding a slash to folders names
Remove GLOB_NOSORT not to sort the array